SkPDFDevice::MarkedContentManager::~MarkedContentManager() { // This does not close the last open mark, that is done in SkPDFDevice::content. // The value of fNextMarksElemId should still be whatever the user set it to.
SkASSERT(!this->hasActiveMark());
}
staticvoid transform_shader(SkPaint* paint, const SkMatrix& ctm) {
SkASSERT(!ctm.isIdentity()); #ifdefined(SK_BUILD_FOR_ANDROID_FRAMEWORK) // A shader's matrix is: CTM x LocalMatrix x WrappingLocalMatrix. We want to // switch to device space, where CTM = I, while keeping the original behavior. // // I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix // LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix // InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix // NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix //
SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
SkMatrix lmInv; if (lm.invert(&lmInv)) {
SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
} return; #endif
paint->setShader(paint->getShader()->makeWithLocalMatrix(ctm));
}
static SkTCopyOnFirstWrite<SkPaint> clean_paint(const SkPaint& srcPaint) {
SkTCopyOnFirstWrite<SkPaint> paint(srcPaint); // If the paint will definitely draw opaquely, replace kSrc with // kSrcOver. http://crbug.com/473572 if (!paint->isSrcOver() &&
SkBlendFastPath::kSrcOver == CheckFastPath(*paint, false))
{
paint.writable()->setBlendMode(SkBlendMode::kSrcOver);
} if (paint->getColorFilter()) { // We assume here that PDFs all draw in sRGB.
SkPaintPriv::RemoveColorFilter(paint.writable(), sk_srgb_singleton());
}
SkASSERT(!paint->getColorFilter()); return paint;
}
/* Calculate an inverted path's equivalent non-inverted path, given the *canvasbounds. *outPathmayaliaswithinvPath(sincethisissupportedbyPathOps).
*/ staticbool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
SkPath* outPath) {
SkASSERT(invPath.isInverseFillType()); if (auto result = Op(SkPath::Rect(bounds), invPath, kIntersect_SkPathOp)) {
*outPath = *result; return true;
} returnfalse;
}
sk_sp<SkDevice> SkPDFDevice::createDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) { // PDF does not support image filters, so render them on CPU. // Note that this rendering is done at "screen" resolution (100dpi), not // printer resolution.
// TODO: It may be possible to express some filters natively using PDF // to improve quality and file size (skbug.com/40034150) if ((layerPaint && (layerPaint->getImageFilter() || layerPaint->getColorFilter()))
|| (cinfo.fInfo.colorSpace() && !cinfo.fInfo.colorSpace()->isSRGB())) { // need to return a raster device, which we will detect in drawDevice() return SkBitmapDevice::Create(cinfo.fInfo,
SkSurfaceProps());
} return sk_make_sp<SkPDFDevice>(cinfo.fInfo.dimensions(), fDocument);
}
// A helper class to automatically finish a ContentEntry at the end of a // drawing method and maintain the state needed between set up and finish. class ScopedContentEntry {
public:
ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack, const SkMatrix& matrix, const SkPaint& paint,
SkScalar textScale = 0)
: fDevice(device)
, fBlendMode(SkBlendMode::kSrcOver)
, fClipStack(clipStack)
{ if (matrix.hasPerspective()) {
NOT_IMPLEMENTED(!matrix.hasPerspective(), false); return;
}
fBlendMode = paint.getBlendMode_or(SkBlendMode::kSrcOver);
fContentStream =
fDevice->setUpContentEntry(clipStack, matrix, paint, textScale, &fDstFormXObject);
}
ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, SkScalar textScale = 0)
: ScopedContentEntry(dev, &dev->cs(), dev->localToDevice(), paint, textScale) {}
/* Returns true when we explicitly need the shape of the drawing. */ bool needShape() { switch (fBlendMode) { case SkBlendMode::kClear: case SkBlendMode::kSrc: case SkBlendMode::kSrcIn: case SkBlendMode::kSrcOut: case SkBlendMode::kDstIn: case SkBlendMode::kDstOut: case SkBlendMode::kSrcATop: case SkBlendMode::kDstATop: case SkBlendMode::kModulate: return true; default: returnfalse;
}
}
/* Returns true unless we only need the shape of the drawing. */ bool needSource() { if (fBlendMode == SkBlendMode::kClear) { returnfalse;
} return true;
}
/* If the shape is different than the alpha component of the content, then *setShapeshouldbecalledwiththeshape.Inparticular,imagesand *deviceshaverectangularshape.
*/ void setShape(const SkPath& shape) {
fShape = shape;
}
void SkPDFDevice::drawAnnotation(const SkRect& rect, constchar key[], SkData* value) { if (!value || !fDocument->hasCurrentPage()) { return;
} // Annotations are specified in absolute coordinates, so the page xform maps from device space // to the global space, and applies the document transform.
SkMatrix pageXform = this->deviceToGlobal().asM33();
pageXform.postConcat(fDocument->currentPageTransform()); if (rect.isEmpty()) { if (!strcmp(key, SkPDFGetElemIdKey())) { int elemId; if (value->size() != sizeof(elemId)) { return; }
memcpy(&elemId, value->data(), sizeof(elemId));
fMarkManager.setNextMarksElemId(elemId); return;
} if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
SkPoint p = this->localToDevice().mapPoint({rect.x(), rect.y()});
p = pageXform.mapPoint(p); auto pg = fDocument->currentPage();
fDocument->fNamedDestinations.push_back(SkPDFNamedDestination{sk_ref_sp(value), p, pg});
} return;
} // Convert to path to handle non-90-degree rotations.
SkPath path = SkPath::Rect(rect).makeTransform(this->localToDevice());
SkPath clip = SkClipStack_AsPath(this->cs()); if (auto result = Op(clip, path, kIntersect_SkPathOp)) {
path = *result;
} // PDF wants a rectangle only.
SkRect transformedRect = pageXform.mapRect(path.getBounds()); if (transformedRect.isEmpty()) { return;
}
if (SkCanvas::kPoints_PointMode != mode) {
set_style(&paint, SkPaint::kStroke_Style);
}
// skcpu::Draw::drawPoints converts to multiple calls to fDevice->drawPath. // We only use this when there's a path effect or perspective because of the overhead // of multiple calls to setUpContentEntry it causes. if (paint->getPathEffect() || this->localToDevice().hasPerspective()) {
draw_points(mode, points, *paint, this->devClipBounds(), this); return;
}
if (mode == SkCanvas::kPoints_PointMode && paint->getStrokeCap() != SkPaint::kRound_Cap) { if (paint->getStrokeWidth()) { // PDF won't draw a single point with square/butt caps because the // orientation is ambiguous. Draw a rectangle instead.
set_style(&paint, SkPaint::kFill_Style);
SkScalar strokeWidth = paint->getStrokeWidth();
SkScalar halfStroke = SkScalarHalf(strokeWidth); for (auto&& pt : points) {
SkRect r = SkRect::MakeXYWH(pt.fX, pt.fY, 0, 0);
r.inset(-halfStroke, -halfStroke);
this->drawRect(r, *paint);
} return;
} else { if (paint->getStrokeCap() != SkPaint::kRound_Cap) {
paint.writable()->setStrokeCap(SkPaint::kRound_Cap);
}
}
}
ScopedContentEntry content(this, *paint); if (!content) { return;
}
SkDynamicMemoryWStream* contentStream = content.stream();
fMarkManager.beginMark(); if (fMarkManager.hasActiveMark()) { // Destinations are in absolute coordinates.
SkMatrix pageXform = this->deviceToGlobal().asM33();
pageXform.postConcat(fDocument->currentPageTransform()); // The points do not already have localToDevice applied.
pageXform.preConcat(this->localToDevice());
for (auto&& userPoint : points) {
fMarkManager.accumulate(pageXform.mapPoint(userPoint));
}
} const size_t count = points.size(); switch (mode) { case SkCanvas::kPolygon_PointMode:
SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream); for (size_t i = 1; i < count; i++) {
SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
}
SkPDFUtils::StrokePath(contentStream); break; case SkCanvas::kLines_PointMode: for (size_t i = 0; i < count/2; i++) {
SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
SkPDFUtils::StrokePath(contentStream);
} break; case SkCanvas::kPoints_PointMode:
SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap); for (size_t i = 0; i < count; i++) {
SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
SkPDFUtils::ClosePath(contentStream);
SkPDFUtils::StrokePath(contentStream);
} break; default:
SkASSERT(false);
}
}
void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) { // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
SkPDFIndirectReference& noSMaskGS = fDocument->fNoSmaskGraphicState; if (!noSMaskGS) {
SkPDFDict tmp("ExtGState");
tmp.insertName("SMask", "None");
noSMaskGS = fDocument->emit(tmp);
}
this->setGraphicState(noSMaskGS, contentStream);
}
if (paint->getMaskFilter()) {
this->internalDrawPathWithFilter(clipStack, ctm, origPath, *paint); return;
}
SkMatrix matrix = ctm;
if (paint->getPathEffect()) { if (clipStack.isEmpty(this->bounds())) { return;
}
SkPathBuilder builder; if (skpathutils::FillPathWithPaint(modifiedPath, *paint, &builder)) {
set_style(&paint, SkPaint::kFill_Style);
} else {
set_style(&paint, SkPaint::kStroke_Style); if (paint->getStrokeWidth() != 0) {
paint.writable()->setStrokeWidth(0);
}
}
modifiedPath = builder.detach();
paint.writable()->setPathEffect(nullptr);
}
if (this->handleInversePath(modifiedPath, *paint)) { return;
} if (matrix.getType() & SkMatrix::kPerspective_Mask) {
modifiedPath = modifiedPath.makeTransform(matrix); if (paint->getShader()) {
transform_shader(paint.writable(), matrix);
}
matrix = SkMatrix::I();
}
ScopedContentEntry content(this, &clipStack, matrix, *paint); if (!content) { return;
}
fMarkManager.beginMark(); if (fMarkManager.hasActiveMark()) { // Destinations are in absolute coordinates.
SkMatrix pageXform = this->deviceToGlobal().asM33();
pageXform.postConcat(fDocument->currentPageTransform()); // The path does not already have localToDevice / ctm / matrix applied.
pageXform.preConcat(matrix);
void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
SkASSERT(!bm.drawsNothing()); auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, SkSamplingOptions(), paint,
SkMatrix::I());
}
// TODO: SkPDFFont has code to handle paints with mask filters, but the viewers do not. // See https://crbug.com/362796158 for Pdfium and b/325266484 for Preview if (this->localToDevice().hasPerspective() || runPaint.getMaskFilter()) {
this->drawGlyphRunAsPath(glyphRun, offset, runPaint); return;
}
// TODO: FontType should probably be on SkPDFStrike?
SkAdvancedTypefaceMetrics::FontType initialFontType = SkPDFFont::FontType(*pdfStrike, *metrics);
SkClusterator clusterator(glyphRun);
// The size, skewX, and scaleX are applied here.
SkScalar textSize = glyphRunFont.getSize();
SkScalar advanceScale = textSize * glyphRunFont.getScaleX() / pdfStrike->fPath.fUnitsPerEM;
// textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
SkScalar textScaleY = textSize / pdfStrike->fPath.fUnitsPerEM;
SkScalar textScaleX = advanceScale + glyphRunFont.getSkewX() * textScaleY;
// Clear everything from the runPaint that will be applied by the strike.
SkPaint fillPaint(runPaint); if (fillPaint.getStrokeWidth() > 0) {
fillPaint.setStroke(false);
}
fillPaint.setPathEffect(nullptr);
fillPaint.setMaskFilter(nullptr);
SkTCopyOnFirstWrite<SkPaint> paint(clean_paint(fillPaint));
ScopedContentEntry content(this, *paint, glyphRunFont.getScaleX()); if (!content) { return;
}
SkDynamicMemoryWStream* out = content.stream();
// Destinations are in absolute coordinates. // The glyphs bounds go through the localToDevice separately for clipping.
SkMatrix pageXform = this->deviceToGlobal().asM33();
pageXform.postConcat(fDocument->currentPageTransform());
fMarkManager.beginMark(); if (!glyphRun.text().empty()) {
fDocument->addStructElemTitle(fMarkManager.elemId(), glyphRun.text());
}
if (clusterator.reversedChars()) {
out->writeText("/ReversedChars BMC\n");
}
SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
GlyphPositioner glyphPositioner(out, glyphRunFont.getSkewX(), offset);
SkPDFFont* font = nullptr;
SkBulkGlyphMetricsAndPaths paths{pdfStrike->fPath.fStrikeSpec}; auto glyphs = paths.glyphs(glyphRun.glyphsIDs());
while (SkClusterator::Cluster c = clusterator.next()) { int glyphIndex = c.fGlyphIndex; int glyphLimit = glyphIndex + c.fGlyphCount;
bool actualText = false;
SK_AT_SCOPE_EXIT(if (actualText) {
glyphPositioner.flush();
out->writeText("EMC\n");
}); if (c.fUtf8Text) { bool toUnicode = false; constchar* textPtr = c.fUtf8Text; constchar* textEnd = c.fUtf8Text + c.fTextByteLength;
SkUnichar clusterUnichar = SkUTF::NextUTF8(&textPtr, textEnd); // ToUnicode can only handle one glyph in a cluster. if (clusterUnichar >= 0 && c.fGlyphCount == 1) {
SkGlyphID gid = glyphIDs[glyphIndex];
SkUnichar fontUnichar = gid < glyphToUnicode.size() ? glyphToUnicode[gid] : 0;
// The regular cmap can handle this if there is one glyph in the cluster, // one code point in the cluster, and the glyph maps to the code point.
toUnicode = textPtr == textEnd && clusterUnichar == fontUnichar;
// The extended cmap can handle this if there is one glyph in the cluster, // the font has no code point for the glyph, // there are less than 512 bytes in the UTF-16, // and the mapping matches or can be added. // UTF-16 uses at most 2x space of UTF-8; 64 code points seems enough. if (!toUnicode && fontUnichar <= 0 && c.fTextByteLength < 256) {
SkString* unicodes = glyphToUnicodeEx.find(gid); if (!unicodes) {
glyphToUnicodeEx.set(gid, SkString(c.fUtf8Text, c.fTextByteLength));
toUnicode = true;
} elseif (unicodes->equals(c.fUtf8Text, c.fTextByteLength)) {
toUnicode = true;
}
}
} if (!toUnicode) {
glyphPositioner.flush(); // Begin marked-content sequence with associated property list.
out->writeText("/Span<</ActualText ");
SkPDFWriteTextString(out, c.fUtf8Text, c.fTextByteLength);
out->writeText(" >> BDC\n");
actualText = true;
}
} for (; glyphIndex < glyphLimit; ++glyphIndex) {
SkGlyphID gid = glyphIDs[glyphIndex]; if (numGlyphs <= gid) { continue;
}
SkPoint xy = glyphRun.positions()[glyphIndex]; // Do a glyph-by-glyph bounds-reject if positions are absolute.
SkRect glyphBounds = get_glyph_bounds_device_space(
glyphs[glyphIndex], textScaleX, textScaleY,
xy + offset, this->localToDevice()); if (glyphBounds.isEmpty()) { if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) { continue;
}
} else { if (!clipStackBounds.intersects(glyphBounds)) { continue; // reject glyphs as out of bounds
}
} if (needs_new_font(font, glyphs[glyphIndex], initialFontType)) { // Not yet specified font or need to switch font.
font = pdfStrike->getFontResource(glyphs[glyphIndex]);
SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
glyphPositioner.setFont(font);
SkPDFWriteResourceName(out, SkPDFResourceType::kFont,
add_resource(fFontResources, font->indirectReference()));
out->writeText(" ");
SkPDFUtils::AppendScalar(textSize, out);
out->writeText(" Tf\n");
std::unique_ptr<SkStreamAsset> SkPDFDevice::content() { if (fActiveStackState.fContentStream) {
fActiveStackState.drainStack();
fActiveStackState = SkPDFGraphicStackState();
} if (fContent.bytesWritten() == 0) { return std::make_unique<SkMemoryStream>();
}
// Implicitly close any still active marked-content sequence. // Must do this before fContent is written to buffer. int elemId = fMarkManager.elemId();
fMarkManager.setNextMarksElemId(0);
fMarkManager.beginMark();
SkDynamicMemoryWStream buffer; if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
} if (fNeedsExtraSave) {
buffer.writeText("q\n");
}
fContent.writeToAndReset(&buffer); if (fNeedsExtraSave) {
buffer.writeText("Q\n");
}
fNeedsExtraSave = false;
// Subsequent use of this SkPDFDevice is still associated with the current structure element.
fMarkManager.setNextMarksElemId(elemId);
/* Draws an inverse filled path by using Path Ops to compute the positive *inverseusingthecurrentclipastheinversebounds. *Returntrueifthiswasaninversepathandwasproperlyhandled, *otherwisereturnsfalseandthenormaldrawingroutineshouldcontinue, *eitherasa(incorrect)fallbackorbecausethepathwasnotinverse *inthefirstplace.
*/ bool SkPDFDevice::handleInversePath(const SkPath& origPath, const SkPaint& srcPaint) { // Assume the caller has already applied the path effect.
SkASSERT(!srcPaint.getPathEffect());
if (!origPath.isInverseFillType()) { returnfalse;
}
SkPDFIndirectReference xobject =
SkPDFMakeFormXObject(fDocument, this->content(),
fMarkManager.structParentsKey(),
SkPDFMakeArray(bounds.left(), bounds.top(),
bounds.right(), bounds.bottom()),
this->makeResourceDict(), inverseTransform, colorSpace); // We always draw the form xobjects that we create back into the device, so // we simply preserve the font usage instead of pulling it out and merging // it back in later.
this->reset(); return xobject;
}
// PDF treats a shader as a color, so we only set one or the other.
SkShader* shader = paint.getShader(); if (shader) { if (as_SB(shader)->type() == SkShaderBase::ShaderType::kColor) { auto colorShader = static_cast<SkColorShader*>(shader); // We don't have to set a shader just for a color.
color = colorShader->color();
color.fA *= paint.getAlphaf();
entry->fColor = colorShader->color().makeOpaque();
} else { // PDF positions patterns relative to the initial transform, so // we need to apply the current transform to the shader parameters.
SkMatrix transform = matrix;
transform.postConcat(initialTransform);
// PDF doesn't support kClamp_TileMode, so we simulate it by making // a pattern the size of the current clip.
SkRect clipStackBounds = clipStack ? clipStack->bounds(deviceBounds)
: SkRect::Make(deviceBounds);
// We need to apply the initial transform to bounds in order to get // bounds in a consistent coordinate system.
initialTransform.mapRect(&clipStackBounds);
SkIRect bounds;
clipStackBounds.roundOut(&bounds);
// Use alpha 1 for the shader, the paint alpha is applied with newGraphicsState (below) auto c = paint.getColor4f();
SkPDFIndirectReference pdfShader = SkPDFMakeShader(doc, shader, transform, bounds,
{c.fR, c.fG, c.fB, 1.0f});
if (pdfShader) { // pdfShader has been canonicalized so we can directly compare pointers.
entry->fShaderIndex = add_resource(*shaderResources, pdfShader);
}
}
}
// Dst xfer mode doesn't draw source at all. if (blendMode == SkBlendMode::kDst) { return nullptr;
}
// For the following modes, we want to handle source and destination // separately, so make an object of what's already there. if (!treat_as_regular_pdf_blend_mode(blendMode) && blendMode != SkBlendMode::kDstOver) { if (!isContentEmpty()) {
*dst = this->makeFormXObjectFromDevice();
SkASSERT(isContentEmpty());
} elseif (blendMode != SkBlendMode::kSrc &&
blendMode != SkBlendMode::kSrcOut) { // Except for Src and SrcOut, if there isn't anything already there, // then we're done. return nullptr;
}
} // TODO(vandebo): Figure out how/if we can handle the following modes: // Xor, Plus. For now, we treat them as SrcOver/Normal.
SkASSERT(dst); // Changing the current content into a form-xobject will destroy the clip // objects which is fine since the xobject will already be clipped. However // if source has shape, we need to clip it too, so a copy of the clip is // saved.
SkPaint stockPaint;
SkPDFIndirectReference srcFormXObject; if (this->isContentEmpty()) { // If nothing was drawn and there's no shape, then the draw was a // no-op, but dst needs to be restored for that to be true. // If there is shape, then an empty source with Src, SrcIn, SrcOut, // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop // reduces to Dst. if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
blendMode == SkBlendMode::kSrcATop) {
ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
this->drawFormXObject(dst, content.stream(), nullptr); return;
} else {
blendMode = SkBlendMode::kClear;
}
} else {
srcFormXObject = this->makeFormXObjectFromDevice();
}
// TODO(vandebo) srcFormXObject may contain alpha, but here we want it // without alpha. if (blendMode == SkBlendMode::kSrcATop) { // TODO(vandebo): In order to properly support SrcATop we have to track // the shape of what's been drawn at all times. It's the intersection of // the non-transparent parts of the device and the outlines (shape) of // all images and devices drawn.
this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, true);
} else { if (shape != nullptr) { // Draw shape into a form-xobject.
SkPaint filledPaint;
filledPaint.setColor(SK_ColorBLACK);
filledPaint.setStyle(SkPaint::kFill_Style);
SkClipStack empty;
SkPDFDevice shapeDev(this->size(), fDocument, fInitialTransform);
shapeDev.internalDrawPath(clipStack ? *clipStack : empty,
SkMatrix::I(), *shape, filledPaint);
this->drawFormXObjectWithMask(dst, shapeDev.makeFormXObjectFromDevice(),
SkBlendMode::kSrcOver, true);
} else {
this->drawFormXObjectWithMask(dst, srcFormXObject, SkBlendMode::kSrcOver, true);
}
}
// First, figure out the src->dst transform and subset the image if needed.
SkIRect bounds = imageSubset.image()->bounds();
SkRect srcRect = src ? *src : SkRect::Make(bounds);
SkMatrix transform = SkMatrix::RectToRectOrIdentity(srcRect, dst);
SkMatrix originalTransform = transform; if (src && *src != SkRect::Make(bounds)) { if (!srcRect.intersect(SkRect::Make(bounds))) { return;
}
srcRect.roundOut(&bounds);
transform.preTranslate(SkIntToScalar(bounds.x()),
SkIntToScalar(bounds.y())); if (bounds != imageSubset.image()->bounds()) {
imageSubset = imageSubset.subset(bounds);
didSubset = true;
} if (!imageSubset) { return;
}
}
// If the image is opaque and the paint's alpha is too, replace // kSrc blendmode with kSrcOver. http://crbug.com/473572
SkTCopyOnFirstWrite<SkPaint> paint(srcPaint); if (!paint->isSrcOver() &&
imageSubset.image()->isOpaque() &&
SkBlendFastPath::kSrcOver == CheckFastPath(*paint, false))
{
paint.writable()->setBlendMode(SkBlendMode::kSrcOver);
}
// Alpha-only images need to get their color from the shader, before // applying the colorfilter. if (imageSubset.image()->isAlphaOnly() && paint->getColorFilter()) { // must blend alpha image and shader before applying colorfilter. auto surface =
SkSurfaces::Raster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
SkCanvas* canvas = surface->getCanvas();
SkPaint tmpPaint; // In the case of alpha images with shaders, the shader's coordinate // system is the image's coordiantes.
tmpPaint.setShader(sk_ref_sp(paint->getShader()));
tmpPaint.setColor4f(paint->getColor4f(), nullptr);
canvas->clear(0x00000000);
canvas->drawImage(imageSubset.image().get(), 0, 0, sampling, &tmpPaint); if (paint->getShader() != nullptr) {
paint.writable()->setShader(nullptr);
}
imageSubset = SkKeyedImage(surface->makeImageSnapshot());
canUseOriginal = false;
SkASSERT(!imageSubset.image()->isAlphaOnly());
}
if (imageSubset.image()->isAlphaOnly()) { // The ColorFilter applies to the paint color/shader, not the alpha layer.
SkASSERT(nullptr == paint->getColorFilter());
sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get()); if (!mask) { return;
} // PDF doesn't seem to allow masking vector graphics with an Image XObject. // Must mask with a Form XObject.
sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
{
SkCanvas canvas(maskDevice); // This clip prevents the mask image shader from covering // entire device if unnecessary.
canvas.clipRect(this->cs().bounds(this->bounds()));
canvas.concat(ctm); if (paint->getMaskFilter()) {
SkPaint tmpPaint;
tmpPaint.setShader(mask->makeShader(SkSamplingOptions(), transform));
tmpPaint.setMaskFilter(sk_ref_sp(paint->getMaskFilter()));
canvas.drawRect(dst, tmpPaint);
} else { if (src && !is_integral(*src)) {
canvas.clipRect(dst);
}
canvas.concat(transform);
canvas.drawImage(mask, 0, 0);
}
}
SkIRect maskDeviceBounds = maskDevice->cs().bounds(maskDevice->bounds()).roundOut(); if (!ctm.isIdentity() && paint->getShader()) {
transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
}
ScopedContentEntry content(this, &this->cs(), SkMatrix::I(), *paint); if (!content) { return;
}
this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
maskDevice->makeFormXObjectFromDevice(maskDeviceBounds, true), false,
SkPDFGraphicState::kLuminosity_SMaskMode, fDocument), content.stream());
SkPDFUtils::AppendRectangle(SkRect::Make(this->size()), content.stream());
SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPathFillType::kWinding, content.stream());
this->clearMaskOnGraphicState(content.stream()); return;
} if (paint->getMaskFilter()) {
paint.writable()->setShader(imageSubset.image()->makeShader(SkSamplingOptions(),
transform));
SkPath path = SkPath::Rect(dst); // handles non-integral clipping.
this->internalDrawPath(this->cs(), this->localToDevice(), path, *paint); return;
}
transform.postConcat(ctm);
originalTransform.postConcat(ctm);
SkMatrix matrix = transform;
// Rasterize the bitmap using perspective in a new bitmap. if (transform.hasPerspective()) { // Transform the bitmap in the new space, without taking into // account the initial transform.
SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
SkPath perspectiveOutline = SkPath::Rect(imageBounds).makeTransform(transform);
// Retrieve the bounds of the new shape.
SkRect outlineBounds = perspectiveOutline.getBounds(); if (!outlineBounds.intersect(SkRect::Make(this->devClipBounds()))) { return;
}
// Transform the bitmap in the new space to the final space, to account for DPI
SkRect physicalBounds = fInitialTransform.mapRect(outlineBounds);
SkScalar scaleX = physicalBounds.width() / outlineBounds.width();
SkScalar scaleY = physicalBounds.height() / outlineBounds.height();
// TODO(edisonn): A better approach would be to use a bitmap shader // (in clamp mode) and draw a rect over the entire bounding box. Then // intersect perspectiveOutline to the clip. That will avoid introducing // alpha to the image while still giving good behavior at the edge of // the image. Avoiding alpha will reduce the pdf size and generation // CPU time some.
// Translate the draw in the new canvas, so we perfectly fit the // shape in the bitmap.
canvas->setMatrix(offsetMatrix);
canvas->drawImage(imageSubset.image(), 0, 0);
// In the new space, we use the identity matrix translated // and scaled to reflect DPI.
matrix.setScale(1 / scaleX, 1 / scaleY);
matrix.postTranslate(deltaX, deltaY);
// Check if SkPDFDevice::createDevice returned an SkBitmapDevice. // SkPDFDevice::createDevice creates SkBitmapDevice for color filters. // Image filters generally go through makeSpecial and drawSpecial.
SkPixmap pmap; if (device->peekPixels(&pmap)) {
this->SkClipStackDevice::drawDevice(device, sampling, paint); return;
}
SkMatrix matrix = device->getRelativeTransform(*this).asM33();
ScopedContentEntry content(this, &this->cs(), matrix, paint); if (!content) { return;
}
SkPath shape = SkPath::Rect(SkRect::Make(device->imageInfo().dimensions()))
.makeTransform(matrix); if (content.needShape()) {
content.setShape(shape);
} if (!content.needSource()) { return;
} // This XObject may contain its own marks, which are hidden if emitted inside an outer mark. // If it does have its own marks any current mark is paused and then re-set after. // If it does not have its own marks it will be part of the content of the current mark. int currentStructElemId = fMarkManager.elemId(); if (pdfDevice->fMarkManager.structParentsKey()) {
fMarkManager.setNextMarksElemId(0);
fMarkManager.beginMark();
}
this->drawFormXObject(pdfDevice->makeFormXObjectFromDevice(), content.stream(), &shape);
fMarkManager.setNextMarksElemId(currentStructElemId);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.