GraphicsContextSkia.cpp 37.5 KB
Newer Older
1 2
/*
 * Copyright (c) 2006, Google Inc. All rights reserved.
3
 *
4 5 6
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
7
 *
8 9 10 11 12 13 14 15 16
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
17
 *
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "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 THE COPYRIGHT
 * OWNER 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 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "GraphicsContext.h"

34
#include "AffineTransform.h"
35 36
#include "Color.h"
#include "FloatRect.h"
37
#include "GLES2Canvas.h"
38
#include "Gradient.h"
39
#include "GraphicsContextPlatformPrivate.h"
40
#include "ImageBuffer.h"
41 42 43 44 45 46 47 48 49
#include "IntRect.h"
#include "NativeImageSkia.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"

#include "SkBitmap.h"
#include "SkBlurDrawLooper.h"
#include "SkCornerPathEffect.h"
#include "SkShader.h"
50 51
#include "SkiaUtils.h"
#include "skia/ext/platform_canvas.h"
52 53 54 55

#include <math.h>
#include <wtf/Assertions.h>
#include <wtf/MathExtras.h>
56
#include <wtf/UnusedParam.h>
57 58 59 60 61 62 63

using namespace std;

namespace WebCore {

namespace {

64 65 66
inline int fastMod(int value, int max)
{
    int sign = SkExtractSign(value);
67

68 69 70 71 72 73 74 75 76 77 78 79 80
    value = SkApplySign(value, sign);
    if (value >= max)
        value %= max;
    return SkApplySign(value, sign);
}

inline float square(float n)
{
    return n * n;
}

}  // namespace

81 82 83 84 85 86 87 88 89
// "Seatbelt" functions ------------------------------------------------------
//
// These functions check certain graphics primitives for being "safe".
// Skia has historically crashed when sent crazy data. These functions do
// additional checking to prevent crashes.
//
// Ideally, all of these would be fixed in the graphics layer and we would not
// have to do any checking. You can uncomment the ENSURE_VALUE_SAFETY_FOR_SKIA
// flag to check the graphics layer.
90 91 92 93

// Disabling these checks (20/01/2010), since we think we've fixed all the Skia
// bugs.  Leaving the code in for now, so we can revert easily if necessary.
// #define ENSURE_VALUE_SAFETY_FOR_SKIA
94

95
#ifdef ENSURE_VALUE_SAFETY_FOR_SKIA
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
static bool isCoordinateSkiaSafe(float coord)
{
    // First check for valid floats.
#if defined(_MSC_VER)
    if (!_finite(coord))
#else
    if (!finite(coord))
#endif
        return false;

    // Skia uses 16.16 fixed point and 26.6 fixed point in various places. If
    // the transformed point exceeds 15 bits, we just declare that it's
    // unreasonable to catch both of these cases.
    static const int maxPointMagnitude = 32767;
    if (coord > maxPointMagnitude || coord < -maxPointMagnitude)
        return false;

    return true;
114
}
115
#endif
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

static bool isPointSkiaSafe(const SkMatrix& transform, const SkPoint& pt)
{
#ifdef ENSURE_VALUE_SAFETY_FOR_SKIA
    // Now check for points that will overflow. We check the *transformed*
    // points since this is what will be rasterized.
    SkPoint xPt;
    transform.mapPoints(&xPt, &pt, 1);
    return isCoordinateSkiaSafe(xPt.fX) && isCoordinateSkiaSafe(xPt.fY);
#else
    return true;
#endif
}

static bool isRectSkiaSafe(const SkMatrix& transform, const SkRect& rc)
{
#ifdef ENSURE_VALUE_SAFETY_FOR_SKIA
    SkPoint topleft = {rc.fLeft, rc.fTop};
    SkPoint bottomright = {rc.fRight, rc.fBottom};
    return isPointSkiaSafe(transform, topleft) && isPointSkiaSafe(transform, bottomright);
#else
    return true;
#endif
}

bool isPathSkiaSafe(const SkMatrix& transform, const SkPath& path)
{
#ifdef ENSURE_VALUE_SAFETY_FOR_SKIA
    SkPoint current_points[4];
    SkPath::Iter iter(path, false);
    for (SkPath::Verb verb = iter.next(current_points);
         verb != SkPath::kDone_Verb;
         verb = iter.next(current_points)) {
        switch (verb) {
        case SkPath::kMove_Verb:
            // This move will be duplicated in the next verb, so we can ignore.
            break;
        case SkPath::kLine_Verb:
            // iter.next returns 2 points.
            if (!isPointSkiaSafe(transform, current_points[0])
                || !isPointSkiaSafe(transform, current_points[1]))
                return false;
            break;
        case SkPath::kQuad_Verb:
            // iter.next returns 3 points.
            if (!isPointSkiaSafe(transform, current_points[0])
                || !isPointSkiaSafe(transform, current_points[1])
                || !isPointSkiaSafe(transform, current_points[2]))
                return false;
            break;
        case SkPath::kCubic_Verb:
            // iter.next returns 4 points.
            if (!isPointSkiaSafe(transform, current_points[0])
                || !isPointSkiaSafe(transform, current_points[1])
                || !isPointSkiaSafe(transform, current_points[2])
                || !isPointSkiaSafe(transform, current_points[3]))
                return false;
            break;
        case SkPath::kClose_Verb:
        case SkPath::kDone_Verb:
        default:
            break;
        }
    }
    return true;
#else
    return true;
#endif
}

// Local helper functions ------------------------------------------------------

void addCornerArc(SkPath* path, const SkRect& rect, const IntSize& size, int startAngle)
{
    SkIRect ir;
    int rx = SkMin32(SkScalarRound(rect.width()), size.width());
    int ry = SkMin32(SkScalarRound(rect.height()), size.height());

    ir.set(-rx, -ry, rx, ry);
    switch (startAngle) {
    case 0:
        ir.offset(rect.fRight - ir.fRight, rect.fBottom - ir.fBottom);
        break;
    case 90:
        ir.offset(rect.fLeft - ir.fLeft, rect.fBottom - ir.fBottom);
        break;
    case 180:
        ir.offset(rect.fLeft - ir.fLeft, rect.fTop - ir.fTop);
        break;
    case 270:
        ir.offset(rect.fRight - ir.fRight, rect.fTop - ir.fTop);
        break;
    default:
        ASSERT(0);
    }

    SkRect r;
    r.set(ir);
    path->arcTo(r, SkIntToScalar(startAngle), SkIntToScalar(90), false);
}

// -----------------------------------------------------------------------------

// This may be called with a NULL pointer to create a graphics context that has
// no painting.
221
void GraphicsContext::platformInit(PlatformGraphicsContext* gc)
222
{
223
    m_data = new GraphicsContextPlatformPrivate(gc);
224 225 226
    setPaintingDisabled(!gc || !platformContext()->canvas());
}

227
void GraphicsContext::platformDestroy()
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
{
    delete m_data;
}

PlatformGraphicsContext* GraphicsContext::platformContext() const
{
    ASSERT(!paintingDisabled());
    return m_data->context();
}

// State saving ----------------------------------------------------------------

void GraphicsContext::savePlatformState()
{
    if (paintingDisabled())
        return;

245 246 247
    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->save();

248 249 250 251 252 253 254 255 256
    // Save our private State.
    platformContext()->save();
}

void GraphicsContext::restorePlatformState()
{
    if (paintingDisabled())
        return;

257 258 259
    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->restore();

260 261 262 263 264 265 266 267 268
    // Restore our private State.
    platformContext()->restore();
}

void GraphicsContext::beginTransparencyLayer(float opacity)
{
    if (paintingDisabled())
        return;

269 270 271 272 273 274 275 276 277
    // We need the "alpha" layer flag here because the base layer is opaque
    // (the surface of the page) but layers on top may have transparent parts.
    // Without explicitly setting the alpha flag, the layer will inherit the
    // opaque setting of the base and some things won't work properly.
    platformContext()->canvas()->saveLayerAlpha(
        0,
        static_cast<unsigned char>(opacity * 255),
        static_cast<SkCanvas::SaveFlags>(SkCanvas::kHasAlphaLayer_SaveFlag |
                                         SkCanvas::kFullColorLayer_SaveFlag));
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
}

void GraphicsContext::endTransparencyLayer()
{
    if (paintingDisabled())
        return;
    platformContext()->canvas()->restore();
}

// Graphics primitives ---------------------------------------------------------

void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness)
{
    if (paintingDisabled())
        return;

    SkRect r(rect);
    if (!isRectSkiaSafe(getCTM(), r))
        return;

298
    platformContext()->prepareForSoftwareDraw();
299 300 301 302
    SkPath path;
    path.addOval(r, SkPath::kCW_Direction);
    // only perform the inset if we won't invert r
    if (2 * thickness < rect.width() && 2 * thickness < rect.height()) {
303 304 305 306
        // Adding one to the thickness doesn't make the border too thick as
        // it's painted over afterwards. But without this adjustment the
        // border appears a little anemic after anti-aliasing.
        r.inset(SkIntToScalar(thickness + 1), SkIntToScalar(thickness + 1));
307 308
        path.addOval(r, SkPath::kCCW_Direction);
    }
309
    platformContext()->clipPathAntiAliased(path);
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
}

void GraphicsContext::addPath(const Path& path)
{
    if (paintingDisabled())
        return;
    platformContext()->addPath(*path.platformPath());
}

void GraphicsContext::beginPath()
{
    if (paintingDisabled())
        return;
    platformContext()->beginPath();
}

void GraphicsContext::clearPlatformShadow()
{
    if (paintingDisabled())
        return;
    platformContext()->setDrawLooper(0);
}

void GraphicsContext::clearRect(const FloatRect& rect)
{
    if (paintingDisabled())
        return;

338
    if (platformContext()->useGPU() && !platformContext()->canvasClipApplied()) {
339 340 341 342 343
        platformContext()->prepareForHardwareDraw();
        platformContext()->gpuCanvas()->clearRect(rect);
        return;
    }

344 345 346
    // Force a readback here (if we're using the GPU), since clearRect() is
    // incompatible with mixed-mode rendering.
    platformContext()->syncSoftwareCanvas();
347

348 349 350 351 352 353
    SkRect r = rect;
    if (!isRectSkiaSafe(getCTM(), r))
        ClipRectToCanvas(*platformContext()->canvas(), r, &r);

    SkPaint paint;
    platformContext()->setupPaintForFilling(&paint);
354
    paint.setXfermodeMode(SkXfermode::kClear_Mode);
355 356 357 358 359 360 361 362 363 364 365 366
    platformContext()->canvas()->drawRect(r, paint);
}

void GraphicsContext::clip(const FloatRect& rect)
{
    if (paintingDisabled())
        return;

    SkRect r(rect);
    if (!isRectSkiaSafe(getCTM(), r))
        return;

367
    platformContext()->prepareForSoftwareDraw();
368 369 370 371
    platformContext()->canvas()->clipRect(r);
}

void GraphicsContext::clip(const Path& path)
372 373 374 375 376 377 378 379
{
    if (paintingDisabled())
        return;

    const SkPath& p = *path.platformPath();
    if (!isPathSkiaSafe(getCTM(), p))
        return;

380
    platformContext()->prepareForSoftwareDraw();
381 382 383 384
    platformContext()->clipPathAntiAliased(p);
}

void GraphicsContext::canvasClip(const Path& path)
385 386 387 388 389 390 391 392
{
    if (paintingDisabled())
        return;

    const SkPath& p = *path.platformPath();
    if (!isPathSkiaSafe(getCTM(), p))
        return;

393
    platformContext()->canvasClipPath(p);
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
}

void GraphicsContext::clipOut(const IntRect& rect)
{
    if (paintingDisabled())
        return;

    SkRect r(rect);
    if (!isRectSkiaSafe(getCTM(), r))
        return;

    platformContext()->canvas()->clipRect(r, SkRegion::kDifference_Op);
}

void GraphicsContext::clipOut(const Path& p)
{
    if (paintingDisabled())
        return;

    const SkPath& path = *p.platformPath();
    if (!isPathSkiaSafe(getCTM(), path))
        return;

    platformContext()->canvas()->clipPath(path, SkRegion::kDifference_Op);
}

420
void GraphicsContext::clipPath(const Path& pathToClip, WindRule clipRule)
421 422 423 424
{
    if (paintingDisabled())
        return;

425 426 427 428
    // FIXME: Be smarter about this.
    beginPath();
    addPath(pathToClip);

429
    SkPath path = platformContext()->currentPathInLocalCoordinates();
430 431 432
    if (!isPathSkiaSafe(getCTM(), path))
        return;

433
    path.setFillType(clipRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType);
434
    platformContext()->clipPathAntiAliased(path);
435 436
}

437 438 439 440
void GraphicsContext::concatCTM(const AffineTransform& affine)
{
    if (paintingDisabled())
        return;
441 442 443 444

    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->concatCTM(affine);

445 446 447
    platformContext()->canvas()->concat(affine);
}

448 449 450 451 452 453 454 455 456 457
void GraphicsContext::drawConvexPolygon(size_t numPoints,
                                        const FloatPoint* points,
                                        bool shouldAntialias)
{
    if (paintingDisabled())
        return;

    if (numPoints <= 1)
        return;

458 459
    platformContext()->prepareForSoftwareDraw();

460 461 462 463 464 465 466 467 468 469 470 471 472 473
    SkPath path;

    path.incReserve(numPoints);
    path.moveTo(WebCoreFloatToSkScalar(points[0].x()),
                WebCoreFloatToSkScalar(points[0].y()));
    for (size_t i = 1; i < numPoints; i++) {
        path.lineTo(WebCoreFloatToSkScalar(points[i].x()),
                    WebCoreFloatToSkScalar(points[i].y()));
    }

    if (!isPathSkiaSafe(getCTM(), path))
        return;

    SkPaint paint;
474 475
    platformContext()->setupPaintForFilling(&paint);
    platformContext()->canvas()->drawPath(path, paint);
476 477 478

    if (strokeStyle() != NoStroke) {
        paint.reset();
479
        platformContext()->setupPaintForStroking(&paint, 0, 0);
480 481 482 483
        platformContext()->canvas()->drawPath(path, paint);
    }
}

484
void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
485 486 487 488 489 490
{
    if (paintingDisabled())
        return;

    if (numPoints <= 1)
        return;
491

492 493 494
    // FIXME: IMPLEMENT!!
}

495 496 497 498 499 500 501 502 503 504
// This method is only used to draw the little circles used in lists.
void GraphicsContext::drawEllipse(const IntRect& elipseRect)
{
    if (paintingDisabled())
        return;

    SkRect rect = elipseRect;
    if (!isRectSkiaSafe(getCTM(), rect))
        return;

505
    platformContext()->prepareForSoftwareDraw();
506
    SkPaint paint;
507 508
    platformContext()->setupPaintForFilling(&paint);
    platformContext()->canvas()->drawOval(rect, paint);
509 510 511

    if (strokeStyle() != NoStroke) {
        paint.reset();
512
        platformContext()->setupPaintForStroking(&paint, &rect, 0);
513 514 515 516
        platformContext()->canvas()->drawOval(rect, paint);
    }
}

517
void GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color)
518 519 520 521
{
    // FIXME: implement
}

522
void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int /* width */, int /* offset */, const Color& color)
523 524 525 526 527
{
    if (paintingDisabled())
        return;

    unsigned rectCount = rects.size();
528
    if (!rectCount)
529 530
        return;

531
    platformContext()->prepareForSoftwareDraw();
532 533 534 535 536 537 538 539 540 541 542 543 544
    SkRegion focusRingRegion;
    const SkScalar focusRingOutset = WebCoreFloatToSkScalar(0.5);
    for (unsigned i = 0; i < rectCount; i++) {
        SkIRect r = rects[i];
        r.inset(-focusRingOutset, -focusRingOutset);
        focusRingRegion.op(r, SkRegion::kUnion_Op);
    }

    SkPath path;
    SkPaint paint;
    paint.setAntiAlias(true);
    paint.setStyle(SkPaint::kStroke_Style);

545
    paint.setColor(color.rgb());
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    paint.setStrokeWidth(focusRingOutset * 2);
    paint.setPathEffect(new SkCornerPathEffect(focusRingOutset * 2))->unref();
    focusRingRegion.getBoundaryPath(&path);
    platformContext()->canvas()->drawPath(path, paint);
}

// This is only used to draw borders.
void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
{
    if (paintingDisabled())
        return;

    StrokeStyle penStyle = strokeStyle();
    if (penStyle == NoStroke)
        return;

    SkPaint paint;
563
    if (!isPointSkiaSafe(getCTM(), point1) || !isPointSkiaSafe(getCTM(), point2))
564 565
        return;

566 567
    platformContext()->prepareForSoftwareDraw();

568 569 570 571 572
    FloatPoint p1 = point1;
    FloatPoint p2 = point2;
    bool isVerticalLine = (p1.x() == p2.x());
    int width = roundf(strokeThickness());

573 574 575
    // We know these are vertical or horizontal lines, so the length will just
    // be the sum of the displacement component vectors give or take 1 -
    // probably worth the speed up of no square root, which also won't be exact.
576 577
    FloatSize disp = p2 - p1;
    int length = SkScalarRound(disp.width() + disp.height());
578
    platformContext()->setupPaintForStroking(&paint, 0, length);
579 580 581 582 583 584

    if (strokeStyle() == DottedStroke || strokeStyle() == DashedStroke) {
        // Do a rect fill of our endpoints.  This ensures we always have the
        // appearance of being a border.  We then draw the actual dotted/dashed line.

        SkRect r1, r2;
585 586
        r1.set(p1.x(), p1.y(), p1.x() + width, p1.y() + width);
        r2.set(p2.x(), p2.y(), p2.x() + width, p2.y() + width);
587 588 589 590 591 592 593 594 595 596 597 598 599

        if (isVerticalLine) {
            r1.offset(-width / 2, 0);
            r2.offset(-width / 2, -width);
        } else {
            r1.offset(0, -width / 2);
            r2.offset(-width, -width / 2);
        }
        SkPaint fillPaint;
        fillPaint.setColor(paint.getColor());
        platformContext()->canvas()->drawRect(r1, fillPaint);
        platformContext()->canvas()->drawRect(r2, fillPaint);
    }
600

601 602
    adjustLineToPixelBoundaries(p1, p2, width, penStyle);
    SkPoint pts[2] = { (SkPoint)p1, (SkPoint)p2 };
603 604 605 606

    platformContext()->canvas()->drawPoints(SkCanvas::kLines_PointMode, 2, pts, paint);
}

607
void GraphicsContext::drawLineForTextChecking(const IntPoint& pt, int width, TextCheckingLineStyle style)
608 609 610 611
{
    if (paintingDisabled())
        return;

612 613
    platformContext()->prepareForSoftwareDraw();

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
    // Create the pattern we'll use to draw the underline.
    static SkBitmap* misspellBitmap = 0;
    if (!misspellBitmap) {
        // We use a 2-pixel-high misspelling indicator because that seems to be
        // what WebKit is designed for, and how much room there is in a typical
        // page for it.
        const int rowPixels = 32;  // Must be multiple of 4 for pattern below.
        const int colPixels = 2;
        misspellBitmap = new SkBitmap;
        misspellBitmap->setConfig(SkBitmap::kARGB_8888_Config,
                                   rowPixels, colPixels);
        misspellBitmap->allocPixels();

        misspellBitmap->eraseARGB(0, 0, 0, 0);
        const uint32_t lineColor = 0xFFFF0000;  // Opaque red.
        const uint32_t antiColor = 0x60600000;  // Semitransparent red.

        // Pattern:  X o   o X o   o X
        //             o X o   o X o
        uint32_t* row1 = misspellBitmap->getAddr32(0, 0);
        uint32_t* row2 = misspellBitmap->getAddr32(0, 1);
        for (int x = 0; x < rowPixels; x++) {
            switch (x % 4) {
            case 0:
                row1[x] = lineColor;
                break;
            case 1:
                row1[x] = antiColor;
                row2[x] = antiColor;
                break;
            case 2:
                row2[x] = lineColor;
                break;
            case 3:
                row1[x] = antiColor;
                row2[x] = antiColor;
                break;
            }
        }
    }

    // Offset it vertically by 1 so that there's some space under the text.
    SkScalar originX = SkIntToScalar(pt.x());
    SkScalar originY = SkIntToScalar(pt.y()) + 1;

    // Make a shader for the bitmap with an origin of the box we'll draw. This
    // shader is refcounted and will have an initial refcount of 1.
    SkShader* shader = SkShader::CreateBitmapShader(
        *misspellBitmap, SkShader::kRepeat_TileMode,
        SkShader::kRepeat_TileMode);
    SkMatrix matrix;
    matrix.reset();
    matrix.postTranslate(originX, originY);
    shader->setLocalMatrix(matrix);

    // Assign the shader to the paint & release our reference. The paint will
    // now own the shader and the shader will be destroyed when the paint goes
    // out of scope.
    SkPaint paint;
    paint.setShader(shader);
    shader->unref();

    SkRect rect;
    rect.set(originX,
             originY,
             originX + SkIntToScalar(width),
             originY + SkIntToScalar(misspellBitmap->height()));
    platformContext()->canvas()->drawRect(rect, paint);
}

void GraphicsContext::drawLineForText(const IntPoint& pt,
                                      int width,
                                      bool printing)
{
    if (paintingDisabled())
        return;

691 692 693
    if (width <= 0)
        return;

694 695
    platformContext()->prepareForSoftwareDraw();

696 697 698 699 700 701 702 703
    int thickness = SkMax32(static_cast<int>(strokeThickness()), 1);
    SkRect r;
    r.fLeft = SkIntToScalar(pt.x());
    r.fTop = SkIntToScalar(pt.y());
    r.fRight = r.fLeft + SkIntToScalar(width);
    r.fBottom = r.fTop + SkIntToScalar(thickness);

    SkPaint paint;
704 705 706
    platformContext()->setupPaintForFilling(&paint);
    // Text lines are drawn using the stroke color.
    paint.setColor(platformContext()->effectiveStrokeColor());
707 708 709 710 711 712 713 714 715
    platformContext()->canvas()->drawRect(r, paint);
}

// Draws a filled rectangle with a stroked border.
void GraphicsContext::drawRect(const IntRect& rect)
{
    if (paintingDisabled())
        return;

716 717
    platformContext()->prepareForSoftwareDraw();

718
    SkRect r = rect;
719
    if (!isRectSkiaSafe(getCTM(), r)) {
720 721
        // See the fillRect below.
        ClipRectToCanvas(*platformContext()->canvas(), r, &r);
722
    }
723 724 725 726

    platformContext()->drawRect(r);
}

727
void GraphicsContext::fillPath(const Path& pathToFill)
728 729 730 731
{
    if (paintingDisabled())
        return;

732 733 734 735
    // FIXME: Be smarter about this.
    beginPath();
    addPath(pathToFill);

736
    SkPath path = platformContext()->currentPathInLocalCoordinates();
737 738 739
    if (!isPathSkiaSafe(getCTM(), path))
      return;

740 741
    platformContext()->prepareForSoftwareDraw();

742
    const GraphicsContextState& state = m_state;
743
    path.setFillType(state.fillRule == RULE_EVENODD ?
744 745 746 747 748 749 750 751 752 753 754 755 756 757
        SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType);

    SkPaint paint;
    platformContext()->setupPaintForFilling(&paint);

    platformContext()->canvas()->drawPath(path, paint);
}

void GraphicsContext::fillRect(const FloatRect& rect)
{
    if (paintingDisabled())
        return;

    SkRect r = rect;
758
    if (!isRectSkiaSafe(getCTM(), r)) {
759 760
        // See the other version of fillRect below.
        ClipRectToCanvas(*platformContext()->canvas(), r, &r);
761
    }
762

763
    if (platformContext()->useGPU() && platformContext()->canAccelerate()) {
764 765 766 767 768
        platformContext()->prepareForHardwareDraw();
        platformContext()->gpuCanvas()->fillRect(rect);
        return;
    }

769 770
    platformContext()->save();

771 772
    platformContext()->prepareForSoftwareDraw();

773 774 775
    SkPaint paint;
    platformContext()->setupPaintForFilling(&paint);
    platformContext()->canvas()->drawRect(r, paint);
776 777

    platformContext()->restore();
778 779
}

780
void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, ColorSpace colorSpace)
781 782 783 784
{
    if (paintingDisabled())
        return;

785
    if (platformContext()->useGPU() && platformContext()->canAccelerate()) {
786 787 788 789 790 791 792
        platformContext()->prepareForHardwareDraw();
        platformContext()->gpuCanvas()->fillRect(rect, color, colorSpace);
        return;
    }

    platformContext()->prepareForSoftwareDraw();

793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
    SkRect r = rect;
    if (!isRectSkiaSafe(getCTM(), r)) {
        // Special case when the rectangle overflows fixed point. This is a
        // workaround to fix bug 1212844. When the input rectangle is very
        // large, it can overflow Skia's internal fixed point rect. This
        // should be fixable in Skia (since the output bitmap isn't that
        // large), but until that is fixed, we try to handle it ourselves.
        //
        // We manually clip the rectangle to the current clip rect. This
        // will prevent overflow. The rectangle will be transformed to the
        // canvas' coordinate space before it is converted to fixed point
        // so we are guaranteed not to overflow after doing this.
        ClipRectToCanvas(*platformContext()->canvas(), r, &r);
    }

    SkPaint paint;
    platformContext()->setupPaintCommon(&paint);
    paint.setColor(color.rgb());
    platformContext()->canvas()->drawRect(r, paint);
}

void GraphicsContext::fillRoundedRect(const IntRect& rect,
                                      const IntSize& topLeft,
                                      const IntSize& topRight,
                                      const IntSize& bottomLeft,
                                      const IntSize& bottomRight,
819 820
                                      const Color& color,
                                      ColorSpace colorSpace)
821 822 823 824
{
    if (paintingDisabled())
        return;

825 826
    platformContext()->prepareForSoftwareDraw();

827 828 829 830 831
    SkRect r = rect;
    if (!isRectSkiaSafe(getCTM(), r))
        // See fillRect().
        ClipRectToCanvas(*platformContext()->canvas(), r, &r);

832 833 834 835 836 837 838
    if (topLeft.width() + topRight.width() > rect.width()
            || bottomLeft.width() + bottomRight.width() > rect.width()
            || topLeft.height() + bottomLeft.height() > rect.height()
            || topRight.height() + bottomRight.height() > rect.height()) {
        // Not all the radii fit, return a rect. This matches the behavior of
        // Path::createRoundedRectangle. Without this we attempt to draw a round
        // shadow for a square box.
839
        fillRect(rect, color, colorSpace);
840 841 842
        return;
    }

843 844 845 846 847 848 849 850 851 852 853
    SkPath path;
    addCornerArc(&path, r, topRight, 270);
    addCornerArc(&path, r, bottomRight, 0);
    addCornerArc(&path, r, bottomLeft, 90);
    addCornerArc(&path, r, topLeft, 180);

    SkPaint paint;
    platformContext()->setupPaintForFilling(&paint);
    platformContext()->canvas()->drawPath(path, paint);
}

854
AffineTransform GraphicsContext::getCTM() const
855
{
856
    const SkMatrix& m = platformContext()->canvas()->getTotalMatrix();
857 858 859 860 861 862
    return AffineTransform(SkScalarToDouble(m.getScaleX()),
                           SkScalarToDouble(m.getSkewY()),
                           SkScalarToDouble(m.getSkewX()),
                           SkScalarToDouble(m.getScaleY()),
                           SkScalarToDouble(m.getTranslateX()),
                           SkScalarToDouble(m.getTranslateY()));
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
}

FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& rect)
{
    // This logic is copied from GraphicsContextCG, eseidel 5/05/08

    // It is not enough just to round to pixels in device space. The rotation
    // part of the affine transform matrix to device space can mess with this
    // conversion if we have a rotating image like the hands of the world clock
    // widget. We just need the scale, so we get the affine transform matrix and
    // extract the scale.

    const SkMatrix& deviceMatrix = platformContext()->canvas()->getTotalMatrix();
    if (deviceMatrix.isIdentity())
        return rect;

    float deviceScaleX = sqrtf(square(deviceMatrix.getScaleX())
        + square(deviceMatrix.getSkewY()));
    float deviceScaleY = sqrtf(square(deviceMatrix.getSkewX())
        + square(deviceMatrix.getScaleY()));

    FloatPoint deviceOrigin(rect.x() * deviceScaleX, rect.y() * deviceScaleY);
    FloatPoint deviceLowerRight((rect.x() + rect.width()) * deviceScaleX,
        (rect.y() + rect.height()) * deviceScaleY);

    deviceOrigin.setX(roundf(deviceOrigin.x()));
    deviceOrigin.setY(roundf(deviceOrigin.y()));
    deviceLowerRight.setX(roundf(deviceLowerRight.x()));
    deviceLowerRight.setY(roundf(deviceLowerRight.y()));

    // Don't let the height or width round to 0 unless either was originally 0
894
    if (deviceOrigin.y() == deviceLowerRight.y() && rect.height())
895
        deviceLowerRight.move(0, 1);
896
    if (deviceOrigin.x() == deviceLowerRight.x() && rect.width())
897 898 899 900 901 902 903 904 905 906 907 908 909
        deviceLowerRight.move(1, 0);

    FloatPoint roundedOrigin(deviceOrigin.x() / deviceScaleX,
        deviceOrigin.y() / deviceScaleY);
    FloatPoint roundedLowerRight(deviceLowerRight.x() / deviceScaleX,
        deviceLowerRight.y() / deviceScaleY);
    return FloatRect(roundedOrigin, roundedLowerRight - roundedOrigin);
}

void GraphicsContext::scale(const FloatSize& size)
{
    if (paintingDisabled())
        return;
910 911 912 913

    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->scale(size);

914 915 916 917 918 919 920 921
    platformContext()->canvas()->scale(WebCoreFloatToSkScalar(size.width()),
        WebCoreFloatToSkScalar(size.height()));
}

void GraphicsContext::setAlpha(float alpha)
{
    if (paintingDisabled())
        return;
922

923 924
    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->setAlpha(alpha);
925

926 927 928
    platformContext()->setAlpha(alpha);
}

929
void GraphicsContext::setPlatformCompositeOperation(CompositeOperator op)
930 931 932
{
    if (paintingDisabled())
        return;
933

934 935
    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->setCompositeOperation(op);
936

937
    platformContext()->setXfermodeMode(WebCoreCompositeToSkiaComposite(op));
938 939
}

940 941 942 943 944
InterpolationQuality GraphicsContext::imageInterpolationQuality() const
{
    return platformContext()->interpolationQuality();
}

945
void GraphicsContext::setImageInterpolationQuality(InterpolationQuality q)
946
{
947
    platformContext()->setInterpolationQuality(q);
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
}

void GraphicsContext::setLineCap(LineCap cap)
{
    if (paintingDisabled())
        return;
    switch (cap) {
    case ButtCap:
        platformContext()->setLineCap(SkPaint::kButt_Cap);
        break;
    case RoundCap:
        platformContext()->setLineCap(SkPaint::kRound_Cap);
        break;
    case SquareCap:
        platformContext()->setLineCap(SkPaint::kSquare_Cap);
        break;
    default:
        ASSERT(0);
        break;
    }
}

void GraphicsContext::setLineDash(const DashArray& dashes, float dashOffset)
{
    if (paintingDisabled())
        return;

    // FIXME: This is lifted directly off SkiaSupport, lines 49-74
    // so it is not guaranteed to work correctly.
    size_t dashLength = dashes.size();
978 979 980 981 982
    if (!dashLength) {
        // If no dash is set, revert to solid stroke
        // FIXME: do we need to set NoStroke in some cases?
        platformContext()->setStrokeStyle(SolidStroke);
        platformContext()->setDashPathEffect(0);
983
        return;
984
    }
985

986
    size_t count = !(dashLength % 2) ? dashLength : dashLength * 2;
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    SkScalar* intervals = new SkScalar[count];

    for (unsigned int i = 0; i < count; i++)
        intervals[i] = dashes[i % dashLength];

    platformContext()->setDashPathEffect(new SkDashPathEffect(intervals, count, dashOffset));

    delete[] intervals;
}

void GraphicsContext::setLineJoin(LineJoin join)
{
    if (paintingDisabled())
        return;
    switch (join) {
    case MiterJoin:
        platformContext()->setLineJoin(SkPaint::kMiter_Join);
        break;
    case RoundJoin:
        platformContext()->setLineJoin(SkPaint::kRound_Join);
        break;
    case BevelJoin:
        platformContext()->setLineJoin(SkPaint::kBevel_Join);
        break;
    default:
        ASSERT(0);
        break;
    }
}

void GraphicsContext::setMiterLimit(float limit)
{
    if (paintingDisabled())
        return;
    platformContext()->setMiterLimit(limit);
}

1024
void GraphicsContext::setPlatformFillColor(const Color& color, ColorSpace colorSpace)
1025 1026 1027
{
    if (paintingDisabled())
        return;
1028

1029 1030 1031
    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->setFillColor(color, colorSpace);

1032 1033 1034
    platformContext()->setFillColor(color.rgb());
}

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
void GraphicsContext::setPlatformFillGradient(Gradient* gradient)
{
    if (paintingDisabled())
        return;

    platformContext()->setFillShader(gradient->platformGradient());
}

void GraphicsContext::setPlatformFillPattern(Pattern* pattern)
{
    if (paintingDisabled())
        return;

1048
    platformContext()->setFillShader(pattern->platformPattern(getCTM()));
1049 1050
}

1051
void GraphicsContext::setPlatformShadow(const FloatSize& size,
1052
                                        float blurFloat,
1053 1054
                                        const Color& color,
                                        ColorSpace colorSpace)
1055 1056 1057 1058
{
    if (paintingDisabled())
        return;

1059
    // Detect when there's no effective shadow and clear the looper.
1060
    if (!size.width() && !size.height() && !blurFloat) {
1061
        platformContext()->setDrawLooper(0);
1062 1063 1064
        return;
    }

1065 1066
    double width = size.width();
    double height = size.height();
1067
    double blur = blurFloat;
1068 1069 1070

    // TODO(tc): This still does not address the issue that shadows
    // within canvas elements should ignore transforms.
1071
    if (m_state.shadowsIgnoreTransforms)  {
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
        // Currently only the GraphicsContext associated with the
        // CanvasRenderingContext for HTMLCanvasElement have shadows ignore
        // Transforms. So with this flag set, we know this state is associated
        // with a CanvasRenderingContext.
        // CG uses natural orientation for Y axis, but the HTML5 canvas spec
        // does not.
        // So we now flip the height since it was flipped in
        // CanvasRenderingContext in order to work with CG.
        height = -height;
    }

    SkColor c;
    if (color.isValid())
        c = color.rgb();
    else
        c = SkColorSetARGB(0xFF/3, 0, 0, 0);    // "std" apple shadow color.

    // TODO(tc): Should we have a max value for the blur?  CG clamps at 1000.0
    // for perf reasons.
    SkDrawLooper* dl = new SkBlurDrawLooper(blur / 2, width, height, c);
    platformContext()->setDrawLooper(dl);
    dl->unref();
}

1096
void GraphicsContext::setPlatformStrokeColor(const Color& strokecolor, ColorSpace colorSpace)
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
{
    if (paintingDisabled())
        return;

    platformContext()->setStrokeColor(strokecolor.rgb());
}

void GraphicsContext::setPlatformStrokeStyle(const StrokeStyle& stroke)
{
    if (paintingDisabled())
        return;

    platformContext()->setStrokeStyle(stroke);
}

void GraphicsContext::setPlatformStrokeThickness(float thickness)
{
    if (paintingDisabled())
        return;

    platformContext()->setStrokeThickness(thickness);
}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
void GraphicsContext::setPlatformStrokeGradient(Gradient* gradient)
{
    if (paintingDisabled())
        return;

    platformContext()->setStrokeShader(gradient->platformGradient());
}

void GraphicsContext::setPlatformStrokePattern(Pattern* pattern)
{
    if (paintingDisabled())
        return;

1133
    platformContext()->setStrokeShader(pattern->platformPattern(getCTM()));
1134 1135
}

1136
void GraphicsContext::setPlatformTextDrawingMode(TextDrawingModeFlags mode)
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
{
    if (paintingDisabled())
        return;

    platformContext()->setTextDrawingMode(mode);
}

void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
{
}

1148
void GraphicsContext::setPlatformShouldAntialias(bool enable)
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
{
    if (paintingDisabled())
        return;

    platformContext()->setUseAntialiasing(enable);
}

void GraphicsContext::strokeArc(const IntRect& r, int startAngle, int angleSpan)
{
    if (paintingDisabled())
        return;

1161 1162
    platformContext()->prepareForSoftwareDraw();

1163 1164 1165 1166 1167 1168 1169 1170
    SkPaint paint;
    SkRect oval = r;
    if (strokeStyle() == NoStroke) {
        // Stroke using the fill color.
        // TODO(brettw) is this really correct? It seems unreasonable.
        platformContext()->setupPaintForFilling(&paint);
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setStrokeWidth(WebCoreFloatToSkScalar(strokeThickness()));
1171 1172
    } else
        platformContext()->setupPaintForStroking(&paint, 0, 0);
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

    // We do this before converting to scalar, so we don't overflow SkFixed.
    startAngle = fastMod(startAngle, 360);
    angleSpan = fastMod(angleSpan, 360);

    SkPath path;
    path.addArc(oval, SkIntToScalar(-startAngle), SkIntToScalar(-angleSpan));
    if (!isPathSkiaSafe(getCTM(), path))
        return;
    platformContext()->canvas()->drawPath(path, paint);
}

1185
void GraphicsContext::strokePath(const Path& pathToStroke)
1186 1187 1188 1189
{
    if (paintingDisabled())
        return;

1190 1191 1192 1193
    // FIXME: Be smarter about this.
    beginPath();
    addPath(pathToStroke);

1194
    SkPath path = platformContext()->currentPathInLocalCoordinates();
1195 1196 1197
    if (!isPathSkiaSafe(getCTM(), path))
        return;

1198 1199
    platformContext()->prepareForSoftwareDraw();

1200
    SkPaint paint;
1201
    platformContext()->setupPaintForStroking(&paint, 0, 0);
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    platformContext()->canvas()->drawPath(path, paint);
}

void GraphicsContext::strokeRect(const FloatRect& rect, float lineWidth)
{
    if (paintingDisabled())
        return;

    if (!isRectSkiaSafe(getCTM(), rect))
        return;

1213 1214
    platformContext()->prepareForSoftwareDraw();

1215
    SkPaint paint;
1216
    platformContext()->setupPaintForStroking(&paint, 0, 0);
1217 1218 1219 1220 1221 1222 1223 1224 1225
    paint.setStrokeWidth(WebCoreFloatToSkScalar(lineWidth));
    platformContext()->canvas()->drawRect(rect, paint);
}

void GraphicsContext::rotate(float angleInRadians)
{
    if (paintingDisabled())
        return;

1226 1227 1228
    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->rotate(angleInRadians);

1229 1230 1231 1232 1233 1234 1235 1236 1237
    platformContext()->canvas()->rotate(WebCoreFloatToSkScalar(
        angleInRadians * (180.0f / 3.14159265f)));
}

void GraphicsContext::translate(float w, float h)
{
    if (paintingDisabled())
        return;

1238 1239 1240
    if (platformContext()->useGPU())
        platformContext()->gpuCanvas()->translate(w, h);

1241 1242 1243 1244
    platformContext()->canvas()->translate(WebCoreFloatToSkScalar(w),
                                           WebCoreFloatToSkScalar(h));
}

1245
void GraphicsContext::syncSoftwareCanvas()
1246
{
1247
    platformContext()->syncSoftwareCanvas();
1248 1249
}

1250
void GraphicsContext::setSharedGraphicsContext3D(SharedGraphicsContext3D* context, DrawingBuffer* framebuffer, const IntSize& size)
1251
{
1252
    platformContext()->setSharedGraphicsContext3D(context, framebuffer, size);
1253 1254
}

1255 1256 1257 1258 1259
void GraphicsContext::markDirtyRect(const IntRect& rect)
{
    platformContext()->markDirtyRect(rect);
}

1260
}  // namespace WebCore