2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkColorFilter.h"
11 #include "SkDrawFilter.h"
12 #include "SkImage_Base.h"
13 #include "SkImageCacherator.h"
14 #include "SkImageFilter.h"
15 #include "SkImageFilterCache.h"
16 #include "SkImagePriv.h"
17 #include "SkLatticeIter.h"
18 #include "SkMetaData.h"
19 #include "SkPatchUtils.h"
20 #include "SkPathPriv.h"
21 #include "SkPathMeasure.h"
22 #include "SkRasterClip.h"
23 #include "SkRSXform.h"
25 #include "SkSpecialImage.h"
26 #include "SkTextBlobRunIterator.h"
27 #include "SkTextToPathIter.h"
30 SkBaseDevice::SkBaseDevice(const SkImageInfo& info, const SkSurfaceProps& surfaceProps)
32 , fSurfaceProps(surfaceProps)
38 SkBaseDevice::~SkBaseDevice() { delete fMetaData; }
40 SkMetaData& SkBaseDevice::getMetaData() {
41 // metadata users are rare, so we lazily allocate it. If that changes we
42 // can decide to just make it a field in the device (rather than a ptr)
43 if (nullptr == fMetaData) {
44 fMetaData = new SkMetaData;
49 #ifdef SK_SUPPORT_LEGACY_ACCESSBITMAP
50 const SkBitmap& SkBaseDevice::accessBitmap(bool changePixels) {
51 const SkBitmap& bitmap = this->onAccessBitmap();
53 bitmap.notifyPixelsChanged();
59 SkPixelGeometry SkBaseDevice::CreateInfo::AdjustGeometry(const SkImageInfo& info,
62 bool preserveLCDText) {
64 case kPossible_TileUsage:
65 // (we think) for compatibility with old clients, we assume this layer can support LCD
66 // even though they may not have marked it as opaque... seems like we should update
67 // our callers (reed/robertphilips).
69 case kNever_TileUsage:
70 if (!preserveLCDText) {
71 geo = kUnknown_SkPixelGeometry;
78 static inline bool is_int(float x) {
79 return x == (float) sk_float_round2int(x);
82 void SkBaseDevice::drawRegion(const SkDraw& draw, const SkRegion& region, const SkPaint& paint) {
83 bool isNonTranslate = draw.fMatrix->getType() & ~(SkMatrix::kTranslate_Mask);
84 bool complexPaint = paint.getStyle() != SkPaint::kFill_Style || paint.getMaskFilter() ||
85 paint.getPathEffect();
86 bool antiAlias = paint.isAntiAlias() && (!is_int(draw.fMatrix->getTranslateX()) ||
87 !is_int(draw.fMatrix->getTranslateY()));
88 if (isNonTranslate || complexPaint || antiAlias) {
90 region.getBoundaryPath(&path);
91 return this->drawPath(draw, path, paint, nullptr, false);
94 SkRegion::Iterator it(region);
96 this->drawRect(draw, SkRect::Make(it.rect()), paint);
101 void SkBaseDevice::drawArc(const SkDraw& draw, const SkRect& oval, SkScalar startAngle,
102 SkScalar sweepAngle, bool useCenter, const SkPaint& paint) {
104 bool isFillNoPathEffect = SkPaint::kFill_Style == paint.getStyle() && !paint.getPathEffect();
105 SkPathPriv::CreateDrawArcPath(&path, oval, startAngle, sweepAngle, useCenter,
107 this->drawPath(draw, path, paint);
110 void SkBaseDevice::drawDRRect(const SkDraw& draw, const SkRRect& outer,
111 const SkRRect& inner, const SkPaint& paint) {
113 path.addRRect(outer);
114 path.addRRect(inner);
115 path.setFillType(SkPath::kEvenOdd_FillType);
116 path.setIsVolatile(true);
118 const SkMatrix* preMatrix = nullptr;
119 const bool pathIsMutable = true;
120 this->drawPath(draw, path, paint, preMatrix, pathIsMutable);
123 void SkBaseDevice::drawPatch(const SkDraw& draw, const SkPoint cubics[12], const SkColor colors[4],
124 const SkPoint texCoords[4], SkBlendMode bmode, const SkPaint& paint) {
125 SkPatchUtils::VertexData data;
127 SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, draw.fMatrix);
129 // It automatically adjusts lodX and lodY in case it exceeds the number of indices.
130 // If it fails to generate the vertices, then we do not draw.
131 if (SkPatchUtils::getVertexData(&data, cubics, colors, texCoords, lod.width(), lod.height())) {
132 this->drawVertices(draw, SkCanvas::kTriangles_VertexMode, data.fVertexCount, data.fPoints,
133 data.fTexCoords, data.fColors, bmode, data.fIndices, data.fIndexCount,
138 void SkBaseDevice::drawTextBlob(const SkDraw& draw, const SkTextBlob* blob, SkScalar x, SkScalar y,
139 const SkPaint &paint, SkDrawFilter* drawFilter) {
141 SkPaint runPaint = paint;
143 SkTextBlobRunIterator it(blob);
144 for (;!it.done(); it.next()) {
145 size_t textLen = it.glyphCount() * sizeof(uint16_t);
146 const SkPoint& offset = it.offset();
147 // applyFontToPaint() always overwrites the exact same attributes,
148 // so it is safe to not re-seed the paint for this reason.
149 it.applyFontToPaint(&runPaint);
151 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
152 // A false return from filter() means we should abort the current draw.
157 runPaint.setFlags(this->filterTextFlags(runPaint));
159 switch (it.positioning()) {
160 case SkTextBlob::kDefault_Positioning:
161 this->drawText(draw, it.glyphs(), textLen, x + offset.x(), y + offset.y(), runPaint);
163 case SkTextBlob::kHorizontal_Positioning:
164 this->drawPosText(draw, it.glyphs(), textLen, it.pos(), 1,
165 SkPoint::Make(x, y + offset.y()), runPaint);
167 case SkTextBlob::kFull_Positioning:
168 this->drawPosText(draw, it.glyphs(), textLen, it.pos(), 2,
169 SkPoint::Make(x, y), runPaint);
172 SkFAIL("unhandled positioning mode");
176 // A draw filter may change the paint arbitrarily, so we must re-seed in this case.
182 bool SkBaseDevice::drawExternallyScaledImage(const SkDraw& draw,
183 const SkImage* image,
186 const SkPaint& paint,
187 SkCanvas::SrcRectConstraint constraint) {
188 SkImageCacherator* cacherator = as_IB(image)->peekCacherator();
193 SkTLazy<SkRect> tmpSrc(src);
194 if (!tmpSrc.isValid()) {
195 tmpSrc.init(SkRect::Make(image->bounds()));
198 SkMatrix m = *draw.fMatrix;
199 m.preConcat(SkMatrix::MakeRectToRect(*tmpSrc.get(), dst, SkMatrix::kFill_ScaleToFit));
201 // constrain src to our bounds
202 if (!image->bounds().contains(*tmpSrc.get()) &&
203 !tmpSrc.get()->intersect(SkRect::Make(image->bounds()))) {
207 SkImageGenerator::ScaledImageRec rec;
208 if (!cacherator->directAccessScaledImage(*tmpSrc.get(), m, paint.getFilterQuality(), &rec)) {
213 if (!bm.installPixels(rec.fPixmap.info(), const_cast<void*>(rec.fPixmap.addr()),
214 rec.fPixmap.rowBytes(), rec.fPixmap.ctable(),
215 rec.fReleaseProc, rec.fReleaseCtx)) {
219 SkTCopyOnFirstWrite<SkPaint> adjustedPaint(paint);
220 if (rec.fQuality != paint.getFilterQuality()) {
221 adjustedPaint.writable()->setFilterQuality(rec.fQuality);
224 this->drawBitmapRect(draw, bm, &rec.fSrcRect, dst, *adjustedPaint, constraint);
228 void SkBaseDevice::drawImage(const SkDraw& draw, const SkImage* image, SkScalar x, SkScalar y,
229 const SkPaint& paint) {
230 // Default impl : turns everything into raster bitmap
231 if (this->drawExternallyScaledImage(draw, image, nullptr,
232 SkRect::Make(image->bounds()).makeOffset(x, y),
233 paint, SkCanvas::kFast_SrcRectConstraint)) {
238 if (as_IB(image)->getROPixels(&bm, this->imageInfo().colorSpace())) {
239 this->drawBitmap(draw, bm, SkMatrix::MakeTrans(x, y), paint);
243 void SkBaseDevice::drawImageRect(const SkDraw& draw, const SkImage* image, const SkRect* src,
244 const SkRect& dst, const SkPaint& paint,
245 SkCanvas::SrcRectConstraint constraint) {
246 // Default impl : turns everything into raster bitmap
247 if (this->drawExternallyScaledImage(draw, image, src, dst, paint, constraint)) {
252 if (as_IB(image)->getROPixels(&bm, this->imageInfo().colorSpace())) {
253 this->drawBitmapRect(draw, bm, src, dst, paint, constraint);
257 void SkBaseDevice::drawImageNine(const SkDraw& draw, const SkImage* image, const SkIRect& center,
258 const SkRect& dst, const SkPaint& paint) {
259 SkLatticeIter iter(image->width(), image->height(), center, dst);
262 while (iter.next(&srcR, &dstR)) {
263 this->drawImageRect(draw, image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
267 void SkBaseDevice::drawBitmapNine(const SkDraw& draw, const SkBitmap& bitmap, const SkIRect& center,
268 const SkRect& dst, const SkPaint& paint) {
269 SkLatticeIter iter(bitmap.width(), bitmap.height(), center, dst);
272 while (iter.next(&srcR, &dstR)) {
273 this->drawBitmapRect(draw, bitmap, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
277 void SkBaseDevice::drawImageLattice(const SkDraw& draw, const SkImage* image,
278 const SkCanvas::Lattice& lattice, const SkRect& dst,
279 const SkPaint& paint) {
280 SkLatticeIter iter(lattice, dst);
283 while (iter.next(&srcR, &dstR)) {
284 this->drawImageRect(draw, image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
288 void SkBaseDevice::drawBitmapLattice(const SkDraw& draw, const SkBitmap& bitmap,
289 const SkCanvas::Lattice& lattice, const SkRect& dst,
290 const SkPaint& paint) {
291 SkLatticeIter iter(lattice, dst);
294 while (iter.next(&srcR, &dstR)) {
295 this->drawBitmapRect(draw, bitmap, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
299 void SkBaseDevice::drawAtlas(const SkDraw& draw, const SkImage* atlas, const SkRSXform xform[],
300 const SkRect tex[], const SkColor colors[], int count,
301 SkBlendMode mode, const SkPaint& paint) {
303 path.setIsVolatile(true);
305 for (int i = 0; i < count; ++i) {
307 xform[i].toQuad(tex[i].width(), tex[i].height(), quad);
310 localM.setRSXform(xform[i]);
311 localM.preTranslate(-tex[i].left(), -tex[i].top());
314 sk_sp<SkShader> shader = atlas->makeShader(SkShader::kClamp_TileMode,
315 SkShader::kClamp_TileMode,
320 pnt.setShader(std::move(shader));
323 pnt.setColorFilter(SkColorFilter::MakeModeFilter(colors[i], (SkBlendMode)mode));
327 path.addPoly(quad, 4, true);
328 path.setConvexity(SkPath::kConvex_Convexity);
329 this->drawPath(draw, path, pnt, nullptr, true);
333 ///////////////////////////////////////////////////////////////////////////////////////////////////
335 void SkBaseDevice::drawSpecial(const SkDraw&, SkSpecialImage*, int x, int y, const SkPaint&) {}
336 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkBitmap&) { return nullptr; }
337 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkImage*) { return nullptr; }
338 sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial() { return nullptr; }
340 ///////////////////////////////////////////////////////////////////////////////////////////////////
342 bool SkBaseDevice::readPixels(const SkImageInfo& info, void* dstP, size_t rowBytes, int x, int y) {
344 SkASSERT(info.width() > 0 && info.height() > 0);
346 SkASSERT(rowBytes >= info.minRowBytes());
347 SkASSERT(x >= 0 && y >= 0);
349 const SkImageInfo& srcInfo = this->imageInfo();
350 SkASSERT(x + info.width() <= srcInfo.width());
351 SkASSERT(y + info.height() <= srcInfo.height());
353 return this->onReadPixels(info, dstP, rowBytes, x, y);
356 bool SkBaseDevice::writePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes,
359 SkASSERT(info.width() > 0 && info.height() > 0);
361 SkASSERT(rowBytes >= info.minRowBytes());
362 SkASSERT(x >= 0 && y >= 0);
364 const SkImageInfo& dstInfo = this->imageInfo();
365 SkASSERT(x + info.width() <= dstInfo.width());
366 SkASSERT(y + info.height() <= dstInfo.height());
368 return this->onWritePixels(info, pixels, rowBytes, x, y);
371 bool SkBaseDevice::onWritePixels(const SkImageInfo&, const void*, size_t, int, int) {
375 bool SkBaseDevice::onReadPixels(const SkImageInfo&, void*, size_t, int x, int y) {
379 bool SkBaseDevice::accessPixels(SkPixmap* pmap) {
380 SkPixmap tempStorage;
381 if (nullptr == pmap) {
384 return this->onAccessPixels(pmap);
387 bool SkBaseDevice::peekPixels(SkPixmap* pmap) {
388 SkPixmap tempStorage;
389 if (nullptr == pmap) {
392 return this->onPeekPixels(pmap);
395 //////////////////////////////////////////////////////////////////////////////////////////
397 static void morphpoints(SkPoint dst[], const SkPoint src[], int count,
398 SkPathMeasure& meas, const SkMatrix& matrix) {
399 SkMatrix::MapXYProc proc = matrix.getMapXYProc();
401 for (int i = 0; i < count; i++) {
405 proc(matrix, src[i].fX, src[i].fY, &pos);
406 SkScalar sx = pos.fX;
407 SkScalar sy = pos.fY;
409 if (!meas.getPosTan(sx, &pos, &tangent)) {
410 // set to 0 if the measure failed, so that we just set dst == pos
414 /* This is the old way (that explains our approach but is way too slow
419 matrix.setSinCos(tangent.fY, tangent.fX);
420 matrix.preTranslate(-sx, 0);
421 matrix.postTranslate(pos.fX, pos.fY);
422 matrix.mapPoints(&dst[i], &pt, 1);
424 dst[i].set(pos.fX - SkScalarMul(tangent.fY, sy),
425 pos.fY + SkScalarMul(tangent.fX, sy));
431 Need differentially more subdivisions when the follow-path is curvy. Not sure how to
432 determine that, but we need it. I guess a cheap answer is let the caller tell us,
433 but that seems like a cop-out. Another answer is to get Rob Johnson to figure it out.
435 static void morphpath(SkPath* dst, const SkPath& src, SkPathMeasure& meas,
436 const SkMatrix& matrix) {
437 SkPath::Iter iter(src, false);
438 SkPoint srcP[4], dstP[3];
441 while ((verb = iter.next(srcP)) != SkPath::kDone_Verb) {
443 case SkPath::kMove_Verb:
444 morphpoints(dstP, srcP, 1, meas, matrix);
445 dst->moveTo(dstP[0]);
447 case SkPath::kLine_Verb:
448 // turn lines into quads to look bendy
449 srcP[0].fX = SkScalarAve(srcP[0].fX, srcP[1].fX);
450 srcP[0].fY = SkScalarAve(srcP[0].fY, srcP[1].fY);
451 morphpoints(dstP, srcP, 2, meas, matrix);
452 dst->quadTo(dstP[0], dstP[1]);
454 case SkPath::kQuad_Verb:
455 morphpoints(dstP, &srcP[1], 2, meas, matrix);
456 dst->quadTo(dstP[0], dstP[1]);
458 case SkPath::kCubic_Verb:
459 morphpoints(dstP, &srcP[1], 3, meas, matrix);
460 dst->cubicTo(dstP[0], dstP[1], dstP[2]);
462 case SkPath::kClose_Verb:
466 SkDEBUGFAIL("unknown verb");
472 void SkBaseDevice::drawTextOnPath(const SkDraw& draw, const void* text, size_t byteLength,
473 const SkPath& follow, const SkMatrix* matrix,
474 const SkPaint& paint) {
475 SkASSERT(byteLength == 0 || text != nullptr);
478 if (text == nullptr || byteLength == 0 || draw.fRC->isEmpty()) {
482 SkTextToPathIter iter((const char*)text, byteLength, paint, true);
483 SkPathMeasure meas(follow, false);
484 SkScalar hOffset = 0;
486 // need to measure first
487 if (paint.getTextAlign() != SkPaint::kLeft_Align) {
488 SkScalar pathLen = meas.getLength();
489 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
490 pathLen = SkScalarHalf(pathLen);
495 const SkPath* iterPath;
497 SkMatrix scaledMatrix;
498 SkScalar scale = iter.getPathScale();
500 scaledMatrix.setScale(scale, scale);
502 while (iter.next(&iterPath, &xpos)) {
505 SkMatrix m(scaledMatrix);
507 tmp.setIsVolatile(true);
508 m.postTranslate(xpos + hOffset, 0);
510 m.postConcat(*matrix);
512 morphpath(&tmp, *iterPath, meas, m);
513 this->drawPath(draw, tmp, iter.getPaint(), nullptr, true);
519 typedef int (*CountTextProc)(const char* text);
520 static int count_utf16(const char* text) {
521 const uint16_t* prev = (uint16_t*)text;
522 (void)SkUTF16_NextUnichar(&prev);
523 return SkToInt((const char*)prev - text);
525 static int return_4(const char* text) { return 4; }
526 static int return_2(const char* text) { return 2; }
528 void SkBaseDevice::drawTextRSXform(const SkDraw& draw, const void* text, size_t len,
529 const SkRSXform xform[], const SkPaint& paint) {
530 CountTextProc proc = nullptr;
531 switch (paint.getTextEncoding()) {
532 case SkPaint::kUTF8_TextEncoding:
533 proc = SkUTF8_CountUTF8Bytes;
535 case SkPaint::kUTF16_TextEncoding:
538 case SkPaint::kUTF32_TextEncoding:
541 case SkPaint::kGlyphID_TextEncoding:
547 SkMatrix localM, currM;
548 const void* stopText = (const char*)text + len;
549 while ((const char*)text < (const char*)stopText) {
550 localM.setRSXform(*xform++);
551 currM.setConcat(*draw.fMatrix, localM);
552 localD.fMatrix = &currM;
553 int subLen = proc((const char*)text);
554 this->drawText(localD, text, subLen, 0, 0, paint);
555 text = (const char*)text + subLen;
559 //////////////////////////////////////////////////////////////////////////////////////////
561 uint32_t SkBaseDevice::filterTextFlags(const SkPaint& paint) const {
562 uint32_t flags = paint.getFlags();
564 if (!paint.isLCDRenderText() || !paint.isAntiAlias()) {
568 if (kUnknown_SkPixelGeometry == fSurfaceProps.pixelGeometry()
569 || this->onShouldDisableLCD(paint)) {
571 flags &= ~SkPaint::kLCDRenderText_Flag;
572 flags |= SkPaint::kGenA8FromLCD_Flag;
578 sk_sp<SkSurface> SkBaseDevice::makeSurface(SkImageInfo const&, SkSurfaceProps const&) {
582 //////////////////////////////////////////////////////////////////////////////////////////
584 void SkBaseDevice::LogDrawScaleFactor(const SkMatrix& matrix, SkFilterQuality filterQuality) {
585 #if SK_HISTOGRAMS_ENABLED
587 kUpscale_ScaleFactor,
588 kNoScale_ScaleFactor,
589 kDownscale_ScaleFactor,
590 kLargeDownscale_ScaleFactor,
592 kLast_ScaleFactor = kLargeDownscale_ScaleFactor
595 float rawScaleFactor = matrix.getMinScale();
597 ScaleFactor scaleFactor;
598 if (rawScaleFactor < 0.5f) {
599 scaleFactor = kLargeDownscale_ScaleFactor;
600 } else if (rawScaleFactor < 1.0f) {
601 scaleFactor = kDownscale_ScaleFactor;
602 } else if (rawScaleFactor > 1.0f) {
603 scaleFactor = kUpscale_ScaleFactor;
605 scaleFactor = kNoScale_ScaleFactor;
608 switch (filterQuality) {
609 case kNone_SkFilterQuality:
610 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.NoneFilterQuality", scaleFactor,
611 kLast_ScaleFactor + 1);
613 case kLow_SkFilterQuality:
614 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.LowFilterQuality", scaleFactor,
615 kLast_ScaleFactor + 1);
617 case kMedium_SkFilterQuality:
618 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.MediumFilterQuality", scaleFactor,
619 kLast_ScaleFactor + 1);
621 case kHigh_SkFilterQuality:
622 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.HighFilterQuality", scaleFactor,
623 kLast_ScaleFactor + 1);
627 // Also log filter quality independent scale factor.
628 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.AnyFilterQuality", scaleFactor,
629 kLast_ScaleFactor + 1);
631 // Also log an overall histogram of filter quality.
632 SK_HISTOGRAM_ENUMERATION("FilterQuality", filterQuality, kLast_SkFilterQuality + 1);