Update configs. IGNORE BROKEN CHANGESETS CLOSED TREE NO BUG a=release ba=release
[gecko.git] / gfx / 2d / DrawTargetCairo.cpp
blob35c2abb48a3354212f009bc3f1004cad95fbe2e2
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "DrawTargetCairo.h"
9 #include "SourceSurfaceCairo.h"
10 #include "PathCairo.h"
11 #include "HelpersCairo.h"
12 #include "BorrowedContext.h"
13 #include "FilterNodeSoftware.h"
14 #include "mozilla/UniquePtr.h"
15 #include "mozilla/Vector.h"
16 #include "mozilla/StaticPrefs_gfx.h"
17 #include "mozilla/StaticPrefs_print.h"
18 #include "nsPrintfCString.h"
20 #include "cairo.h"
21 #include "cairo-tee.h"
22 #include <string.h>
24 #include "Blur.h"
25 #include "Logging.h"
26 #include "Tools.h"
28 #ifdef CAIRO_HAS_QUARTZ_SURFACE
29 # include "cairo-quartz.h"
30 # ifdef MOZ_WIDGET_COCOA
31 # include <ApplicationServices/ApplicationServices.h>
32 # endif
33 #endif
35 #ifdef CAIRO_HAS_XLIB_SURFACE
36 # include "cairo-xlib.h"
37 #endif
39 #ifdef CAIRO_HAS_WIN32_SURFACE
40 # include "cairo-win32.h"
41 #endif
43 #define PIXMAN_DONT_DEFINE_STDINT
44 #include "pixman.h"
46 #include <algorithm>
48 // 2^23
49 #define CAIRO_COORD_MAX (Float(0x7fffff))
51 namespace mozilla {
52 namespace gfx {
54 cairo_surface_t* DrawTargetCairo::mDummySurface;
56 namespace {
58 // An RAII class to prepare to draw a context and optional path. Saves and
59 // restores the context on construction/destruction.
60 class AutoPrepareForDrawing {
61 public:
62 AutoPrepareForDrawing(DrawTargetCairo* dt, cairo_t* ctx) : mCtx(ctx) {
63 dt->PrepareForDrawing(ctx);
64 cairo_save(mCtx);
65 MOZ_ASSERT(cairo_status(mCtx) ||
66 dt->GetTransform().FuzzyEquals(GetTransform()));
69 AutoPrepareForDrawing(DrawTargetCairo* dt, cairo_t* ctx, const Path* path)
70 : mCtx(ctx) {
71 dt->PrepareForDrawing(ctx, path);
72 cairo_save(mCtx);
73 MOZ_ASSERT(cairo_status(mCtx) ||
74 dt->GetTransform().FuzzyEquals(GetTransform()));
77 ~AutoPrepareForDrawing() {
78 cairo_restore(mCtx);
79 cairo_status_t status = cairo_status(mCtx);
80 if (status) {
81 gfxWarning() << "DrawTargetCairo context in error state: "
82 << cairo_status_to_string(status) << "(" << status << ")";
86 private:
87 #ifdef DEBUG
88 Matrix GetTransform() {
89 cairo_matrix_t mat;
90 cairo_get_matrix(mCtx, &mat);
91 return Matrix(mat.xx, mat.yx, mat.xy, mat.yy, mat.x0, mat.y0);
93 #endif
95 cairo_t* mCtx;
98 /* Clamp r to (0,0) (2^23,2^23)
99 * these are to be device coordinates.
101 * Returns false if the rectangle is completely out of bounds,
102 * true otherwise.
104 * This function assumes that it will be called with a rectangle being
105 * drawn into a surface with an identity transformation matrix; that
106 * is, anything above or to the left of (0,0) will be offscreen.
108 * First it checks if the rectangle is entirely beyond
109 * CAIRO_COORD_MAX; if so, it can't ever appear on the screen --
110 * false is returned.
112 * Then it shifts any rectangles with x/y < 0 so that x and y are = 0,
113 * and adjusts the width and height appropriately. For example, a
114 * rectangle from (0,-5) with dimensions (5,10) will become a
115 * rectangle from (0,0) with dimensions (5,5).
117 * If after negative x/y adjustment to 0, either the width or height
118 * is negative, then the rectangle is completely offscreen, and
119 * nothing is drawn -- false is returned.
121 * Finally, if x+width or y+height are greater than CAIRO_COORD_MAX,
122 * the width and height are clamped such x+width or y+height are equal
123 * to CAIRO_COORD_MAX, and true is returned.
125 static bool ConditionRect(Rect& r) {
126 // if either x or y is way out of bounds;
127 // note that we don't handle negative w/h here
128 if (r.X() > CAIRO_COORD_MAX || r.Y() > CAIRO_COORD_MAX) return false;
130 if (r.X() < 0.f) {
131 r.SetWidth(r.XMost());
132 if (r.Width() < 0.f) return false;
133 r.MoveToX(0.f);
136 if (r.XMost() > CAIRO_COORD_MAX) {
137 r.SetRightEdge(CAIRO_COORD_MAX);
140 if (r.Y() < 0.f) {
141 r.SetHeight(r.YMost());
142 if (r.Height() < 0.f) return false;
144 r.MoveToY(0.f);
147 if (r.YMost() > CAIRO_COORD_MAX) {
148 r.SetBottomEdge(CAIRO_COORD_MAX);
150 return true;
153 } // end anonymous namespace
155 static bool SupportsSelfCopy(cairo_surface_t* surface) {
156 switch (cairo_surface_get_type(surface)) {
157 #ifdef CAIRO_HAS_QUARTZ_SURFACE
158 case CAIRO_SURFACE_TYPE_QUARTZ:
159 return true;
160 #endif
161 #ifdef CAIRO_HAS_WIN32_SURFACE
162 case CAIRO_SURFACE_TYPE_WIN32:
163 case CAIRO_SURFACE_TYPE_WIN32_PRINTING:
164 return true;
165 #endif
166 default:
167 return false;
171 static bool PatternIsCompatible(const Pattern& aPattern) {
172 switch (aPattern.GetType()) {
173 case PatternType::LINEAR_GRADIENT: {
174 const LinearGradientPattern& pattern =
175 static_cast<const LinearGradientPattern&>(aPattern);
176 return pattern.mStops->GetBackendType() == BackendType::CAIRO;
178 case PatternType::RADIAL_GRADIENT: {
179 const RadialGradientPattern& pattern =
180 static_cast<const RadialGradientPattern&>(aPattern);
181 return pattern.mStops->GetBackendType() == BackendType::CAIRO;
183 case PatternType::CONIC_GRADIENT: {
184 const ConicGradientPattern& pattern =
185 static_cast<const ConicGradientPattern&>(aPattern);
186 return pattern.mStops->GetBackendType() == BackendType::CAIRO;
188 default:
189 return true;
193 static cairo_user_data_key_t surfaceDataKey;
195 static void ReleaseData(void* aData) {
196 DataSourceSurface* data = static_cast<DataSourceSurface*>(aData);
197 data->Unmap();
198 data->Release();
201 static cairo_surface_t* CopyToImageSurface(unsigned char* aData,
202 const IntRect& aRect,
203 int32_t aStride,
204 SurfaceFormat aFormat) {
205 MOZ_ASSERT(aData);
207 auto aRectWidth = aRect.Width();
208 auto aRectHeight = aRect.Height();
210 cairo_surface_t* surf = cairo_image_surface_create(
211 GfxFormatToCairoFormat(aFormat), aRectWidth, aRectHeight);
212 // In certain scenarios, requesting larger than 8k image fails. Bug 803568
213 // covers the details of how to run into it, but the full detailed
214 // investigation hasn't been done to determine the underlying cause. We
215 // will just handle the failure to allocate the surface to avoid a crash.
216 if (cairo_surface_status(surf)) {
217 gfxWarning() << "Invalid surface DTC " << cairo_surface_status(surf);
218 return nullptr;
221 unsigned char* surfData = cairo_image_surface_get_data(surf);
222 int surfStride = cairo_image_surface_get_stride(surf);
223 int32_t pixelWidth = BytesPerPixel(aFormat);
225 unsigned char* source = aData + aRect.Y() * aStride + aRect.X() * pixelWidth;
227 MOZ_ASSERT(aStride >= aRectWidth * pixelWidth);
228 for (int32_t y = 0; y < aRectHeight; ++y) {
229 memcpy(surfData + y * surfStride, source + y * aStride,
230 aRectWidth * pixelWidth);
232 cairo_surface_mark_dirty(surf);
233 return surf;
237 * If aSurface can be represented as a surface of type
238 * CAIRO_SURFACE_TYPE_IMAGE then returns that surface. Does
239 * not add a reference.
241 static cairo_surface_t* GetAsImageSurface(cairo_surface_t* aSurface) {
242 if (cairo_surface_get_type(aSurface) == CAIRO_SURFACE_TYPE_IMAGE) {
243 return aSurface;
244 #ifdef CAIRO_HAS_WIN32_SURFACE
245 } else if (cairo_surface_get_type(aSurface) == CAIRO_SURFACE_TYPE_WIN32) {
246 return cairo_win32_surface_get_image(aSurface);
247 #endif
250 return nullptr;
253 static cairo_surface_t* CreateSubImageForData(unsigned char* aData,
254 const IntRect& aRect, int aStride,
255 SurfaceFormat aFormat) {
256 if (!aData) {
257 gfxWarning() << "DrawTargetCairo.CreateSubImageForData null aData";
258 return nullptr;
260 unsigned char* data =
261 aData + aRect.Y() * aStride + aRect.X() * BytesPerPixel(aFormat);
263 cairo_surface_t* image = cairo_image_surface_create_for_data(
264 data, GfxFormatToCairoFormat(aFormat), aRect.Width(), aRect.Height(),
265 aStride);
266 // Set the subimage's device offset so that in remains in the same place
267 // relative to the parent
268 cairo_surface_set_device_offset(image, -aRect.X(), -aRect.Y());
269 return image;
273 * Returns a referenced cairo_surface_t representing the
274 * sub-image specified by aSubImage.
276 static cairo_surface_t* ExtractSubImage(cairo_surface_t* aSurface,
277 const IntRect& aSubImage,
278 SurfaceFormat aFormat) {
279 // No need to worry about retaining a reference to the original
280 // surface since the only caller of this function guarantees
281 // that aSurface will stay alive as long as the result
283 cairo_surface_t* image = GetAsImageSurface(aSurface);
284 if (image) {
285 image =
286 CreateSubImageForData(cairo_image_surface_get_data(image), aSubImage,
287 cairo_image_surface_get_stride(image), aFormat);
288 return image;
291 cairo_surface_t* similar = cairo_surface_create_similar(
292 aSurface, cairo_surface_get_content(aSurface), aSubImage.Width(),
293 aSubImage.Height());
295 cairo_t* ctx = cairo_create(similar);
296 cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
297 cairo_set_source_surface(ctx, aSurface, -aSubImage.X(), -aSubImage.Y());
298 cairo_paint(ctx);
299 cairo_destroy(ctx);
301 cairo_surface_set_device_offset(similar, -aSubImage.X(), -aSubImage.Y());
302 return similar;
306 * Returns cairo surface for the given SourceSurface.
307 * If possible, it will use the cairo_surface associated with aSurface,
308 * otherwise, it will create a new cairo_surface.
309 * In either case, the caller must call cairo_surface_destroy on the
310 * result when it is done with it.
312 static cairo_surface_t* GetCairoSurfaceForSourceSurface(
313 SourceSurface* aSurface, bool aExistingOnly = false,
314 const IntRect& aSubImage = IntRect()) {
315 if (!aSurface) {
316 return nullptr;
319 IntRect subimage = IntRect(IntPoint(), aSurface->GetSize());
320 if (!aSubImage.IsEmpty()) {
321 MOZ_ASSERT(!aExistingOnly);
322 MOZ_ASSERT(subimage.Contains(aSubImage));
323 subimage = aSubImage;
326 if (aSurface->GetType() == SurfaceType::CAIRO) {
327 cairo_surface_t* surf =
328 static_cast<SourceSurfaceCairo*>(aSurface)->GetSurface();
329 if (aSubImage.IsEmpty()) {
330 cairo_surface_reference(surf);
331 } else {
332 surf = ExtractSubImage(surf, subimage, aSurface->GetFormat());
334 return surf;
337 if (aSurface->GetType() == SurfaceType::CAIRO_IMAGE) {
338 cairo_surface_t* surf =
339 static_cast<const DataSourceSurfaceCairo*>(aSurface)->GetSurface();
340 if (aSubImage.IsEmpty()) {
341 cairo_surface_reference(surf);
342 } else {
343 surf = ExtractSubImage(surf, subimage, aSurface->GetFormat());
345 return surf;
348 if (aExistingOnly) {
349 return nullptr;
352 RefPtr<DataSourceSurface> data = aSurface->GetDataSurface();
353 if (!data) {
354 return nullptr;
357 DataSourceSurface::MappedSurface map;
358 if (!data->Map(DataSourceSurface::READ, &map)) {
359 return nullptr;
362 cairo_surface_t* surf = CreateSubImageForData(map.mData, subimage,
363 map.mStride, data->GetFormat());
365 // In certain scenarios, requesting larger than 8k image fails. Bug 803568
366 // covers the details of how to run into it, but the full detailed
367 // investigation hasn't been done to determine the underlying cause. We
368 // will just handle the failure to allocate the surface to avoid a crash.
369 if (!surf || cairo_surface_status(surf)) {
370 if (surf && (cairo_surface_status(surf) == CAIRO_STATUS_INVALID_STRIDE)) {
371 // If we failed because of an invalid stride then copy into
372 // a new surface with a stride that cairo chooses. No need to
373 // set user data since we're not dependent on the original
374 // data.
375 cairo_surface_t* result = CopyToImageSurface(
376 map.mData, subimage, map.mStride, data->GetFormat());
377 data->Unmap();
378 return result;
380 data->Unmap();
381 return nullptr;
384 cairo_surface_set_user_data(surf, &surfaceDataKey, data.forget().take(),
385 ReleaseData);
386 return surf;
389 // An RAII class to temporarily clear any device offset set
390 // on a surface. Note that this does not take a reference to the
391 // surface.
392 class AutoClearDeviceOffset final {
393 public:
394 explicit AutoClearDeviceOffset(SourceSurface* aSurface)
395 : mSurface(nullptr), mX(0), mY(0) {
396 Init(aSurface);
399 explicit AutoClearDeviceOffset(const Pattern& aPattern)
400 : mSurface(nullptr), mX(0.0), mY(0.0) {
401 if (aPattern.GetType() == PatternType::SURFACE) {
402 const SurfacePattern& pattern =
403 static_cast<const SurfacePattern&>(aPattern);
404 Init(pattern.mSurface);
408 ~AutoClearDeviceOffset() {
409 if (mSurface) {
410 cairo_surface_set_device_offset(mSurface, mX, mY);
414 private:
415 void Init(SourceSurface* aSurface) {
416 cairo_surface_t* surface = GetCairoSurfaceForSourceSurface(aSurface, true);
417 if (surface) {
418 Init(surface);
419 cairo_surface_destroy(surface);
423 void Init(cairo_surface_t* aSurface) {
424 mSurface = aSurface;
425 cairo_surface_get_device_offset(mSurface, &mX, &mY);
426 cairo_surface_set_device_offset(mSurface, 0, 0);
429 cairo_surface_t* mSurface;
430 double mX;
431 double mY;
434 static inline void CairoPatternAddGradientStop(cairo_pattern_t* aPattern,
435 const GradientStop& aStop,
436 Float aNudge = 0) {
437 cairo_pattern_add_color_stop_rgba(aPattern, aStop.offset + aNudge,
438 aStop.color.r, aStop.color.g, aStop.color.b,
439 aStop.color.a);
442 // Never returns nullptr. As such, you must always pass in Cairo-compatible
443 // patterns, most notably gradients with a GradientStopCairo.
444 // The pattern returned must have cairo_pattern_destroy() called on it by the
445 // caller.
446 // As the cairo_pattern_t returned may depend on the Pattern passed in, the
447 // lifetime of the cairo_pattern_t returned must not exceed the lifetime of the
448 // Pattern passed in.
449 static cairo_pattern_t* GfxPatternToCairoPattern(const Pattern& aPattern,
450 Float aAlpha,
451 const Matrix& aTransform) {
452 cairo_pattern_t* pat;
453 const Matrix* matrix = nullptr;
455 switch (aPattern.GetType()) {
456 case PatternType::COLOR: {
457 DeviceColor color = static_cast<const ColorPattern&>(aPattern).mColor;
458 pat = cairo_pattern_create_rgba(color.r, color.g, color.b,
459 color.a * aAlpha);
460 break;
463 case PatternType::SURFACE: {
464 const SurfacePattern& pattern =
465 static_cast<const SurfacePattern&>(aPattern);
466 cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(
467 pattern.mSurface, false, pattern.mSamplingRect);
468 if (!surf) return nullptr;
470 pat = cairo_pattern_create_for_surface(surf);
472 matrix = &pattern.mMatrix;
474 cairo_pattern_set_filter(
475 pat, GfxSamplingFilterToCairoFilter(pattern.mSamplingFilter));
476 cairo_pattern_set_extend(pat,
477 GfxExtendToCairoExtend(pattern.mExtendMode));
479 cairo_surface_destroy(surf);
480 break;
482 case PatternType::LINEAR_GRADIENT: {
483 const LinearGradientPattern& pattern =
484 static_cast<const LinearGradientPattern&>(aPattern);
486 pat = cairo_pattern_create_linear(pattern.mBegin.x, pattern.mBegin.y,
487 pattern.mEnd.x, pattern.mEnd.y);
489 MOZ_ASSERT(pattern.mStops->GetBackendType() == BackendType::CAIRO);
490 GradientStopsCairo* cairoStops =
491 static_cast<GradientStopsCairo*>(pattern.mStops.get());
492 cairo_pattern_set_extend(
493 pat, GfxExtendToCairoExtend(cairoStops->GetExtendMode()));
495 matrix = &pattern.mMatrix;
497 const std::vector<GradientStop>& stops = cairoStops->GetStops();
498 for (size_t i = 0; i < stops.size(); ++i) {
499 CairoPatternAddGradientStop(pat, stops[i]);
502 break;
504 case PatternType::RADIAL_GRADIENT: {
505 const RadialGradientPattern& pattern =
506 static_cast<const RadialGradientPattern&>(aPattern);
508 pat = cairo_pattern_create_radial(pattern.mCenter1.x, pattern.mCenter1.y,
509 pattern.mRadius1, pattern.mCenter2.x,
510 pattern.mCenter2.y, pattern.mRadius2);
512 MOZ_ASSERT(pattern.mStops->GetBackendType() == BackendType::CAIRO);
513 GradientStopsCairo* cairoStops =
514 static_cast<GradientStopsCairo*>(pattern.mStops.get());
515 cairo_pattern_set_extend(
516 pat, GfxExtendToCairoExtend(cairoStops->GetExtendMode()));
518 matrix = &pattern.mMatrix;
520 const std::vector<GradientStop>& stops = cairoStops->GetStops();
521 for (size_t i = 0; i < stops.size(); ++i) {
522 CairoPatternAddGradientStop(pat, stops[i]);
525 break;
527 case PatternType::CONIC_GRADIENT: {
528 // XXX(ntim): Bug 1617039 - Implement conic-gradient for Cairo
529 pat = cairo_pattern_create_rgba(0.0, 0.0, 0.0, 0.0);
531 break;
533 default: {
534 // We should support all pattern types!
535 MOZ_ASSERT(false);
539 // The pattern matrix is a matrix that transforms the pattern into user
540 // space. Cairo takes a matrix that converts from user space to pattern
541 // space. Cairo therefore needs the inverse.
542 if (matrix) {
543 cairo_matrix_t mat;
544 GfxMatrixToCairoMatrix(*matrix, mat);
545 cairo_matrix_invert(&mat);
546 cairo_pattern_set_matrix(pat, &mat);
549 return pat;
552 static bool NeedIntermediateSurface(const Pattern& aPattern,
553 const DrawOptions& aOptions) {
554 // We pre-multiply colours' alpha by the global alpha, so we don't need to
555 // use an intermediate surface for them.
556 if (aPattern.GetType() == PatternType::COLOR) return false;
558 if (aOptions.mAlpha == 1.0) return false;
560 return true;
563 DrawTargetCairo::DrawTargetCairo()
564 : mContext(nullptr),
565 mSurface(nullptr),
566 mTransformSingular(false),
567 mLockedBits(nullptr),
568 mFontOptions(nullptr) {}
570 DrawTargetCairo::~DrawTargetCairo() {
571 cairo_destroy(mContext);
572 if (mSurface) {
573 cairo_surface_destroy(mSurface);
574 mSurface = nullptr;
576 if (mFontOptions) {
577 cairo_font_options_destroy(mFontOptions);
578 mFontOptions = nullptr;
580 MOZ_ASSERT(!mLockedBits);
583 bool DrawTargetCairo::IsValid() const {
584 return mSurface && !cairo_surface_status(mSurface) && mContext &&
585 !cairo_surface_status(cairo_get_group_target(mContext));
588 DrawTargetType DrawTargetCairo::GetType() const {
589 if (mContext) {
590 cairo_surface_type_t type = cairo_surface_get_type(mSurface);
591 if (type == CAIRO_SURFACE_TYPE_TEE) {
592 type = cairo_surface_get_type(cairo_tee_surface_index(mSurface, 0));
593 MOZ_ASSERT(type != CAIRO_SURFACE_TYPE_TEE, "C'mon!");
594 MOZ_ASSERT(
595 type == cairo_surface_get_type(cairo_tee_surface_index(mSurface, 1)),
596 "What should we do here?");
598 switch (type) {
599 case CAIRO_SURFACE_TYPE_PDF:
600 case CAIRO_SURFACE_TYPE_PS:
601 case CAIRO_SURFACE_TYPE_SVG:
602 case CAIRO_SURFACE_TYPE_WIN32_PRINTING:
603 case CAIRO_SURFACE_TYPE_XML:
604 return DrawTargetType::VECTOR;
606 case CAIRO_SURFACE_TYPE_VG:
607 case CAIRO_SURFACE_TYPE_GL:
608 case CAIRO_SURFACE_TYPE_GLITZ:
609 case CAIRO_SURFACE_TYPE_QUARTZ:
610 case CAIRO_SURFACE_TYPE_DIRECTFB:
611 return DrawTargetType::HARDWARE_RASTER;
613 case CAIRO_SURFACE_TYPE_SKIA:
614 case CAIRO_SURFACE_TYPE_QT:
615 MOZ_FALLTHROUGH_ASSERT(
616 "Can't determine actual DrawTargetType for DrawTargetCairo - "
617 "assuming SOFTWARE_RASTER");
618 case CAIRO_SURFACE_TYPE_IMAGE:
619 case CAIRO_SURFACE_TYPE_XLIB:
620 case CAIRO_SURFACE_TYPE_XCB:
621 case CAIRO_SURFACE_TYPE_WIN32:
622 case CAIRO_SURFACE_TYPE_BEOS:
623 case CAIRO_SURFACE_TYPE_OS2:
624 case CAIRO_SURFACE_TYPE_QUARTZ_IMAGE:
625 case CAIRO_SURFACE_TYPE_SCRIPT:
626 case CAIRO_SURFACE_TYPE_RECORDING:
627 case CAIRO_SURFACE_TYPE_DRM:
628 case CAIRO_SURFACE_TYPE_SUBSURFACE:
629 case CAIRO_SURFACE_TYPE_TEE: // included to silence warning about
630 // unhandled enum value
631 return DrawTargetType::SOFTWARE_RASTER;
632 default:
633 MOZ_CRASH("GFX: Unsupported cairo surface type");
636 MOZ_ASSERT(false, "Could not determine DrawTargetType for DrawTargetCairo");
637 return DrawTargetType::SOFTWARE_RASTER;
640 IntSize DrawTargetCairo::GetSize() const { return mSize; }
642 SurfaceFormat GfxFormatForCairoSurface(cairo_surface_t* surface) {
643 cairo_surface_type_t type = cairo_surface_get_type(surface);
644 if (type == CAIRO_SURFACE_TYPE_IMAGE) {
645 return CairoFormatToGfxFormat(cairo_image_surface_get_format(surface));
647 #ifdef CAIRO_HAS_XLIB_SURFACE
648 // xlib is currently the only Cairo backend that creates 16bpp surfaces
649 if (type == CAIRO_SURFACE_TYPE_XLIB &&
650 cairo_xlib_surface_get_depth(surface) == 16) {
651 return SurfaceFormat::R5G6B5_UINT16;
653 #endif
654 return CairoContentToGfxFormat(cairo_surface_get_content(surface));
657 // We need to \-escape any single-quotes in the destination and URI strings,
658 // in order to pass them via the attributes arg to cairo_tag_begin.
660 // We also need to escape any backslashes (bug 1748077), as per doc at
661 // https://www.cairographics.org/manual/cairo-Tags-and-Links.html#cairo-tag-begin
663 // (Encoding of non-ASCII chars etc gets handled later by the PDF backend.)
664 static void EscapeForCairo(nsACString& aStr) {
665 for (size_t i = aStr.Length(); i > 0;) {
666 --i;
667 if (aStr[i] == '\'') {
668 aStr.ReplaceLiteral(i, 1, "\\'");
669 } else if (aStr[i] == '\\') {
670 aStr.ReplaceLiteral(i, 1, "\\\\");
675 void DrawTargetCairo::Link(const char* aDest, const char* aURI,
676 const Rect& aRect) {
677 if ((!aURI || !*aURI) && (!aDest || !*aDest)) {
678 // No destination? Just bail out.
679 return;
682 double x = aRect.x, y = aRect.y, w = aRect.width, h = aRect.height;
683 cairo_user_to_device(mContext, &x, &y);
684 cairo_user_to_device_distance(mContext, &w, &h);
685 nsPrintfCString attributes("rect=[%f %f %f %f]", x, y, w, h);
687 if (aDest && *aDest) {
688 nsAutoCString dest(aDest);
689 EscapeForCairo(dest);
690 attributes.AppendPrintf(" dest='%s'", dest.get());
692 if (aURI && *aURI) {
693 nsAutoCString uri(aURI);
694 EscapeForCairo(uri);
695 attributes.AppendPrintf(" uri='%s'", uri.get());
698 // We generate a begin/end pair with no content in between, because we are
699 // using the rect attribute of the begin tag to specify the link region
700 // rather than depending on cairo to accumulate the painted area.
701 cairo_tag_begin(mContext, CAIRO_TAG_LINK, attributes.get());
702 cairo_tag_end(mContext, CAIRO_TAG_LINK);
705 void DrawTargetCairo::Destination(const char* aDestination,
706 const Point& aPoint) {
707 if (!aDestination || !*aDestination) {
708 // No destination? Just bail out.
709 return;
712 nsAutoCString dest(aDestination);
713 EscapeForCairo(dest);
715 double x = aPoint.x, y = aPoint.y;
716 cairo_user_to_device(mContext, &x, &y);
718 nsPrintfCString attributes("name='%s' x=%f y=%f internal", dest.get(), x, y);
719 cairo_tag_begin(mContext, CAIRO_TAG_DEST, attributes.get());
720 cairo_tag_end(mContext, CAIRO_TAG_DEST);
723 already_AddRefed<SourceSurface> DrawTargetCairo::Snapshot() {
724 if (!IsValid()) {
725 gfxCriticalNote << "DrawTargetCairo::Snapshot with bad surface "
726 << hexa(mSurface) << ", context " << hexa(mContext)
727 << ", status "
728 << (mSurface ? cairo_surface_status(mSurface) : -1);
729 return nullptr;
731 if (mSnapshot) {
732 RefPtr<SourceSurface> snapshot(mSnapshot);
733 return snapshot.forget();
736 IntSize size = GetSize();
738 mSnapshot = new SourceSurfaceCairo(mSurface, size,
739 GfxFormatForCairoSurface(mSurface), this);
740 RefPtr<SourceSurface> snapshot(mSnapshot);
741 return snapshot.forget();
744 bool DrawTargetCairo::LockBits(uint8_t** aData, IntSize* aSize,
745 int32_t* aStride, SurfaceFormat* aFormat,
746 IntPoint* aOrigin) {
747 cairo_surface_t* target = cairo_get_group_target(mContext);
748 cairo_surface_t* surf = target;
749 #ifdef CAIRO_HAS_WIN32_SURFACE
750 if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_WIN32) {
751 cairo_surface_t* imgsurf = cairo_win32_surface_get_image(surf);
752 if (imgsurf) {
753 surf = imgsurf;
756 #endif
757 if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_IMAGE &&
758 cairo_surface_status(surf) == CAIRO_STATUS_SUCCESS) {
759 PointDouble offset;
760 cairo_surface_get_device_offset(target, &offset.x.value, &offset.y.value);
761 // verify the device offset can be converted to integers suitable for a
762 // bounds rect
763 IntPoint origin(int32_t(-offset.x), int32_t(-offset.y));
764 if (-PointDouble(origin) != offset || (!aOrigin && origin != IntPoint())) {
765 return false;
768 WillChange();
769 Flush();
771 mLockedBits = cairo_image_surface_get_data(surf);
772 *aData = mLockedBits;
773 *aSize = IntSize(cairo_image_surface_get_width(surf),
774 cairo_image_surface_get_height(surf));
775 *aStride = cairo_image_surface_get_stride(surf);
776 *aFormat = CairoFormatToGfxFormat(cairo_image_surface_get_format(surf));
777 if (aOrigin) {
778 *aOrigin = origin;
780 return true;
783 return false;
786 void DrawTargetCairo::ReleaseBits(uint8_t* aData) {
787 MOZ_ASSERT(mLockedBits == aData);
788 mLockedBits = nullptr;
789 cairo_surface_t* surf = cairo_get_group_target(mContext);
790 #ifdef CAIRO_HAS_WIN32_SURFACE
791 if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_WIN32) {
792 cairo_surface_t* imgsurf = cairo_win32_surface_get_image(surf);
793 if (imgsurf) {
794 cairo_surface_mark_dirty(imgsurf);
797 #endif
798 cairo_surface_mark_dirty(surf);
801 void DrawTargetCairo::Flush() {
802 cairo_surface_t* surf = cairo_get_group_target(mContext);
803 cairo_surface_flush(surf);
806 void DrawTargetCairo::PrepareForDrawing(cairo_t* aContext,
807 const Path* aPath /* = nullptr */) {
808 WillChange(aPath);
811 cairo_surface_t* DrawTargetCairo::GetDummySurface() {
812 if (mDummySurface) {
813 return mDummySurface;
816 mDummySurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1);
818 return mDummySurface;
821 static void PaintWithAlpha(cairo_t* aContext, const DrawOptions& aOptions) {
822 if (aOptions.mCompositionOp == CompositionOp::OP_SOURCE) {
823 // Cairo treats the source operator like a lerp when alpha is < 1.
824 // Approximate the desired operator by: out = 0; out += src*alpha;
825 if (aOptions.mAlpha == 1) {
826 cairo_set_operator(aContext, CAIRO_OPERATOR_SOURCE);
827 cairo_paint(aContext);
828 } else {
829 cairo_set_operator(aContext, CAIRO_OPERATOR_CLEAR);
830 cairo_paint(aContext);
831 cairo_set_operator(aContext, CAIRO_OPERATOR_ADD);
832 cairo_paint_with_alpha(aContext, aOptions.mAlpha);
834 } else {
835 cairo_set_operator(aContext, GfxOpToCairoOp(aOptions.mCompositionOp));
836 cairo_paint_with_alpha(aContext, aOptions.mAlpha);
840 void DrawTargetCairo::DrawSurface(SourceSurface* aSurface, const Rect& aDest,
841 const Rect& aSource,
842 const DrawSurfaceOptions& aSurfOptions,
843 const DrawOptions& aOptions) {
844 if (mTransformSingular || aDest.IsEmpty()) {
845 return;
848 if (!IsValid() || !aSurface) {
849 gfxCriticalNote << "DrawSurface with bad surface "
850 << cairo_surface_status(cairo_get_group_target(mContext));
851 return;
854 AutoPrepareForDrawing prep(this, mContext);
855 AutoClearDeviceOffset clear(aSurface);
857 float sx = aSource.Width() / aDest.Width();
858 float sy = aSource.Height() / aDest.Height();
860 cairo_matrix_t src_mat;
861 cairo_matrix_init_translate(&src_mat, aSource.X() - aSurface->GetRect().x,
862 aSource.Y() - aSurface->GetRect().y);
863 cairo_matrix_scale(&src_mat, sx, sy);
865 cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(aSurface);
866 if (!surf) {
867 gfxWarning()
868 << "Failed to create cairo surface for DrawTargetCairo::DrawSurface";
869 return;
871 cairo_pattern_t* pat = cairo_pattern_create_for_surface(surf);
872 cairo_surface_destroy(surf);
874 cairo_pattern_set_matrix(pat, &src_mat);
875 cairo_pattern_set_filter(
876 pat, GfxSamplingFilterToCairoFilter(aSurfOptions.mSamplingFilter));
877 // For PDF output, we avoid using EXTEND_PAD here because floating-point
878 // error accumulation may lead cairo_pdf_surface to conclude that padding
879 // is needed due to an apparent one- or two-pixel mismatch between source
880 // pattern and destination rect sizes when we're rendering a pdf.js page,
881 // and this forces undesirable fallback to the rasterization codepath
882 // instead of simply replaying the recording.
883 // (See bug 1777209.)
884 cairo_pattern_set_extend(
885 pat, cairo_surface_get_type(mSurface) == CAIRO_SURFACE_TYPE_PDF
886 ? CAIRO_EXTEND_NONE
887 : CAIRO_EXTEND_PAD);
889 cairo_set_antialias(mContext,
890 GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
892 // If the destination rect covers the entire clipped area, then unbounded and
893 // bounded operations are identical, and we don't need to push a group.
894 bool needsGroup = !IsOperatorBoundByMask(aOptions.mCompositionOp) &&
895 !aDest.Contains(GetUserSpaceClip());
897 cairo_translate(mContext, aDest.X(), aDest.Y());
899 if (needsGroup) {
900 cairo_push_group(mContext);
901 cairo_new_path(mContext);
902 cairo_rectangle(mContext, 0, 0, aDest.Width(), aDest.Height());
903 cairo_set_source(mContext, pat);
904 cairo_fill(mContext);
905 cairo_pop_group_to_source(mContext);
906 } else {
907 cairo_new_path(mContext);
908 cairo_rectangle(mContext, 0, 0, aDest.Width(), aDest.Height());
909 cairo_clip(mContext);
910 cairo_set_source(mContext, pat);
913 PaintWithAlpha(mContext, aOptions);
915 cairo_pattern_destroy(pat);
918 void DrawTargetCairo::DrawFilter(FilterNode* aNode, const Rect& aSourceRect,
919 const Point& aDestPoint,
920 const DrawOptions& aOptions) {
921 FilterNodeSoftware* filter = static_cast<FilterNodeSoftware*>(aNode);
922 filter->Draw(this, aSourceRect, aDestPoint, aOptions);
925 void DrawTargetCairo::DrawSurfaceWithShadow(SourceSurface* aSurface,
926 const Point& aDest,
927 const ShadowOptions& aShadow,
928 CompositionOp aOperator) {
929 if (!IsValid() || !aSurface) {
930 gfxCriticalNote << "DrawSurfaceWithShadow with bad surface "
931 << cairo_surface_status(cairo_get_group_target(mContext));
932 return;
935 if (aSurface->GetType() != SurfaceType::CAIRO) {
936 return;
939 AutoClearDeviceOffset clear(aSurface);
941 Float width = Float(aSurface->GetSize().width);
942 Float height = Float(aSurface->GetSize().height);
944 SourceSurfaceCairo* source = static_cast<SourceSurfaceCairo*>(aSurface);
945 cairo_surface_t* sourcesurf = source->GetSurface();
946 cairo_surface_t* blursurf;
947 cairo_surface_t* surf;
949 // We only use the A8 surface for blurred shadows. Unblurred shadows can just
950 // use the RGBA surface directly.
951 if (cairo_surface_get_type(sourcesurf) == CAIRO_SURFACE_TYPE_TEE) {
952 blursurf = cairo_tee_surface_index(sourcesurf, 0);
953 surf = cairo_tee_surface_index(sourcesurf, 1);
954 } else {
955 blursurf = sourcesurf;
956 surf = sourcesurf;
959 if (aShadow.mSigma != 0.0f) {
960 MOZ_ASSERT(cairo_surface_get_type(blursurf) == CAIRO_SURFACE_TYPE_IMAGE);
961 Rect extents(0, 0, width, height);
962 AlphaBoxBlur blur(extents, cairo_image_surface_get_stride(blursurf),
963 aShadow.mSigma, aShadow.mSigma);
964 blur.Blur(cairo_image_surface_get_data(blursurf));
967 WillChange();
968 ClearSurfaceForUnboundedSource(aOperator);
970 cairo_save(mContext);
971 cairo_set_operator(mContext, GfxOpToCairoOp(aOperator));
972 cairo_identity_matrix(mContext);
973 cairo_translate(mContext, aDest.x, aDest.y);
975 bool needsGroup = !IsOperatorBoundByMask(aOperator);
976 if (needsGroup) {
977 cairo_push_group(mContext);
980 cairo_set_source_rgba(mContext, aShadow.mColor.r, aShadow.mColor.g,
981 aShadow.mColor.b, aShadow.mColor.a);
982 cairo_mask_surface(mContext, blursurf, aShadow.mOffset.x, aShadow.mOffset.y);
984 if (blursurf != surf || aSurface->GetFormat() != SurfaceFormat::A8) {
985 // Now that the shadow has been drawn, we can draw the surface on top.
986 cairo_set_source_surface(mContext, surf, 0, 0);
987 cairo_new_path(mContext);
988 cairo_rectangle(mContext, 0, 0, width, height);
989 cairo_fill(mContext);
992 if (needsGroup) {
993 cairo_pop_group_to_source(mContext);
994 cairo_paint(mContext);
997 cairo_restore(mContext);
1000 void DrawTargetCairo::DrawPattern(const Pattern& aPattern,
1001 const StrokeOptions& aStrokeOptions,
1002 const DrawOptions& aOptions,
1003 DrawPatternType aDrawType,
1004 bool aPathBoundsClip) {
1005 if (!PatternIsCompatible(aPattern)) {
1006 return;
1009 AutoClearDeviceOffset clear(aPattern);
1011 cairo_pattern_t* pat =
1012 GfxPatternToCairoPattern(aPattern, aOptions.mAlpha, GetTransform());
1013 if (!pat) {
1014 return;
1016 if (cairo_pattern_status(pat)) {
1017 cairo_pattern_destroy(pat);
1018 gfxWarning() << "Invalid pattern";
1019 return;
1022 cairo_set_source(mContext, pat);
1024 cairo_set_antialias(mContext,
1025 GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
1027 if (NeedIntermediateSurface(aPattern, aOptions) ||
1028 (!IsOperatorBoundByMask(aOptions.mCompositionOp) && !aPathBoundsClip)) {
1029 cairo_push_group_with_content(mContext, CAIRO_CONTENT_COLOR_ALPHA);
1031 // Don't want operators to be applied twice
1032 cairo_set_operator(mContext, CAIRO_OPERATOR_OVER);
1034 if (aDrawType == DRAW_STROKE) {
1035 SetCairoStrokeOptions(mContext, aStrokeOptions);
1036 cairo_stroke_preserve(mContext);
1037 } else {
1038 cairo_fill_preserve(mContext);
1041 cairo_pop_group_to_source(mContext);
1043 // Now draw the content using the desired operator
1044 PaintWithAlpha(mContext, aOptions);
1045 } else {
1046 cairo_set_operator(mContext, GfxOpToCairoOp(aOptions.mCompositionOp));
1048 if (aDrawType == DRAW_STROKE) {
1049 SetCairoStrokeOptions(mContext, aStrokeOptions);
1050 cairo_stroke_preserve(mContext);
1051 } else {
1052 cairo_fill_preserve(mContext);
1056 cairo_pattern_destroy(pat);
1059 void DrawTargetCairo::FillRect(const Rect& aRect, const Pattern& aPattern,
1060 const DrawOptions& aOptions) {
1061 if (mTransformSingular) {
1062 return;
1065 AutoPrepareForDrawing prep(this, mContext);
1067 bool restoreTransform = false;
1068 Matrix mat;
1069 Rect r = aRect;
1071 /* Clamp coordinates to work around a design bug in cairo */
1072 if (r.Width() > CAIRO_COORD_MAX || r.Height() > CAIRO_COORD_MAX ||
1073 r.X() < -CAIRO_COORD_MAX || r.X() > CAIRO_COORD_MAX ||
1074 r.Y() < -CAIRO_COORD_MAX || r.Y() > CAIRO_COORD_MAX) {
1075 if (!mat.IsRectilinear()) {
1076 gfxWarning() << "DrawTargetCairo::FillRect() misdrawing huge Rect "
1077 "with non-rectilinear transform";
1080 mat = GetTransform();
1081 r = mat.TransformBounds(r);
1083 if (!ConditionRect(r)) {
1084 gfxWarning() << "Ignoring DrawTargetCairo::FillRect() call with "
1085 "out-of-bounds Rect";
1086 return;
1089 restoreTransform = true;
1090 SetTransform(Matrix());
1093 cairo_new_path(mContext);
1094 cairo_rectangle(mContext, r.X(), r.Y(), r.Width(), r.Height());
1096 bool pathBoundsClip = false;
1098 if (r.Contains(GetUserSpaceClip())) {
1099 pathBoundsClip = true;
1102 DrawPattern(aPattern, StrokeOptions(), aOptions, DRAW_FILL, pathBoundsClip);
1104 if (restoreTransform) {
1105 SetTransform(mat);
1109 void DrawTargetCairo::CopySurfaceInternal(cairo_surface_t* aSurface,
1110 const IntRect& aSource,
1111 const IntPoint& aDest) {
1112 if (cairo_surface_status(aSurface)) {
1113 gfxWarning() << "Invalid surface" << cairo_surface_status(aSurface);
1114 return;
1117 cairo_identity_matrix(mContext);
1119 cairo_set_source_surface(mContext, aSurface, aDest.x - aSource.X(),
1120 aDest.y - aSource.Y());
1121 cairo_set_operator(mContext, CAIRO_OPERATOR_SOURCE);
1122 cairo_set_antialias(mContext, CAIRO_ANTIALIAS_NONE);
1124 cairo_reset_clip(mContext);
1125 cairo_new_path(mContext);
1126 cairo_rectangle(mContext, aDest.x, aDest.y, aSource.Width(),
1127 aSource.Height());
1128 cairo_fill(mContext);
1131 void DrawTargetCairo::CopySurface(SourceSurface* aSurface,
1132 const IntRect& aSource,
1133 const IntPoint& aDest) {
1134 if (mTransformSingular) {
1135 return;
1138 AutoPrepareForDrawing prep(this, mContext);
1139 AutoClearDeviceOffset clear(aSurface);
1141 if (!aSurface) {
1142 gfxWarning() << "Unsupported surface type specified";
1143 return;
1146 cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(aSurface);
1147 if (!surf) {
1148 gfxWarning() << "Unsupported surface type specified";
1149 return;
1152 CopySurfaceInternal(surf, aSource, aDest);
1153 cairo_surface_destroy(surf);
1156 void DrawTargetCairo::CopyRect(const IntRect& aSource, const IntPoint& aDest) {
1157 if (mTransformSingular) {
1158 return;
1161 AutoPrepareForDrawing prep(this, mContext);
1163 IntRect source = aSource;
1164 cairo_surface_t* surf = mSurface;
1166 if (!SupportsSelfCopy(mSurface) && aSource.ContainsY(aDest.y)) {
1167 cairo_surface_t* similar = cairo_surface_create_similar(
1168 mSurface, GfxFormatToCairoContent(GetFormat()), aSource.Width(),
1169 aSource.Height());
1170 cairo_t* ctx = cairo_create(similar);
1171 cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
1172 cairo_set_source_surface(ctx, surf, -aSource.X(), -aSource.Y());
1173 cairo_paint(ctx);
1174 cairo_destroy(ctx);
1176 source.MoveTo(0, 0);
1177 surf = similar;
1180 CopySurfaceInternal(surf, source, aDest);
1182 if (surf != mSurface) {
1183 cairo_surface_destroy(surf);
1187 void DrawTargetCairo::ClearRect(const Rect& aRect) {
1188 if (mTransformSingular) {
1189 return;
1192 AutoPrepareForDrawing prep(this, mContext);
1194 if (!mContext || aRect.Width() < 0 || aRect.Height() < 0 ||
1195 !std::isfinite(aRect.X()) || !std::isfinite(aRect.Width()) ||
1196 !std::isfinite(aRect.Y()) || !std::isfinite(aRect.Height())) {
1197 gfxCriticalNote << "ClearRect with invalid argument " << gfx::hexa(mContext)
1198 << " with " << aRect.Width() << "x" << aRect.Height()
1199 << " [" << aRect.X() << ", " << aRect.Y() << "]";
1202 cairo_set_antialias(mContext, CAIRO_ANTIALIAS_NONE);
1203 cairo_new_path(mContext);
1204 cairo_set_operator(mContext, CAIRO_OPERATOR_CLEAR);
1205 cairo_rectangle(mContext, aRect.X(), aRect.Y(), aRect.Width(),
1206 aRect.Height());
1207 cairo_fill(mContext);
1210 void DrawTargetCairo::StrokeRect(
1211 const Rect& aRect, const Pattern& aPattern,
1212 const StrokeOptions& aStrokeOptions /* = StrokeOptions() */,
1213 const DrawOptions& aOptions /* = DrawOptions() */) {
1214 if (mTransformSingular) {
1215 return;
1218 AutoPrepareForDrawing prep(this, mContext);
1220 cairo_new_path(mContext);
1221 cairo_rectangle(mContext, aRect.X(), aRect.Y(), aRect.Width(),
1222 aRect.Height());
1224 DrawPattern(aPattern, aStrokeOptions, aOptions, DRAW_STROKE);
1227 void DrawTargetCairo::StrokeLine(
1228 const Point& aStart, const Point& aEnd, const Pattern& aPattern,
1229 const StrokeOptions& aStrokeOptions /* = StrokeOptions() */,
1230 const DrawOptions& aOptions /* = DrawOptions() */) {
1231 if (mTransformSingular) {
1232 return;
1235 AutoPrepareForDrawing prep(this, mContext);
1237 cairo_new_path(mContext);
1238 cairo_move_to(mContext, aStart.x, aStart.y);
1239 cairo_line_to(mContext, aEnd.x, aEnd.y);
1241 DrawPattern(aPattern, aStrokeOptions, aOptions, DRAW_STROKE);
1244 void DrawTargetCairo::Stroke(
1245 const Path* aPath, const Pattern& aPattern,
1246 const StrokeOptions& aStrokeOptions /* = StrokeOptions() */,
1247 const DrawOptions& aOptions /* = DrawOptions() */) {
1248 if (mTransformSingular) {
1249 return;
1252 AutoPrepareForDrawing prep(this, mContext, aPath);
1254 if (aPath->GetBackendType() != BackendType::CAIRO) return;
1256 PathCairo* path =
1257 const_cast<PathCairo*>(static_cast<const PathCairo*>(aPath));
1258 path->SetPathOnContext(mContext);
1260 DrawPattern(aPattern, aStrokeOptions, aOptions, DRAW_STROKE);
1263 void DrawTargetCairo::Fill(const Path* aPath, const Pattern& aPattern,
1264 const DrawOptions& aOptions /* = DrawOptions() */) {
1265 if (mTransformSingular) {
1266 return;
1269 AutoPrepareForDrawing prep(this, mContext, aPath);
1271 if (aPath->GetBackendType() != BackendType::CAIRO) return;
1273 PathCairo* path =
1274 const_cast<PathCairo*>(static_cast<const PathCairo*>(aPath));
1275 path->SetPathOnContext(mContext);
1277 DrawPattern(aPattern, StrokeOptions(), aOptions, DRAW_FILL);
1280 bool DrawTargetCairo::IsCurrentGroupOpaque() {
1281 cairo_surface_t* surf = cairo_get_group_target(mContext);
1283 if (!surf) {
1284 return false;
1287 return cairo_surface_get_content(surf) == CAIRO_CONTENT_COLOR;
1290 void DrawTargetCairo::SetFontOptions(cairo_antialias_t aAAMode) {
1291 // This will attempt to detect if the currently set scaled font on the
1292 // context has enabled subpixel AA. If it is not permitted, then it will
1293 // downgrade to grayscale AA.
1294 // This only currently works effectively for the cairo-ft backend relative
1295 // to system defaults, as only cairo-ft reflect system defaults in the scaled
1296 // font state. However, this will work for cairo-ft on both tree Cairo and
1297 // system Cairo.
1298 // Other backends leave the CAIRO_ANTIALIAS_DEFAULT setting untouched while
1299 // potentially interpreting it as subpixel or even other types of AA that
1300 // can't be safely equivocated with grayscale AA. For this reason we don't
1301 // try to also detect and modify the default AA setting, only explicit
1302 // subpixel AA. These other backends must instead rely on tree Cairo's
1303 // cairo_surface_set_subpixel_antialiasing extension.
1305 // If allowing subpixel AA, then leave Cairo's default AA state.
1306 if (mPermitSubpixelAA && aAAMode == CAIRO_ANTIALIAS_DEFAULT) {
1307 return;
1310 if (!mFontOptions) {
1311 mFontOptions = cairo_font_options_create();
1312 if (!mFontOptions) {
1313 gfxWarning() << "Failed allocating Cairo font options";
1314 return;
1318 cairo_get_font_options(mContext, mFontOptions);
1319 cairo_antialias_t oldAA = cairo_font_options_get_antialias(mFontOptions);
1320 cairo_antialias_t newAA =
1321 aAAMode == CAIRO_ANTIALIAS_DEFAULT ? oldAA : aAAMode;
1322 // Nothing to change if switching to default AA.
1323 if (newAA == CAIRO_ANTIALIAS_DEFAULT) {
1324 return;
1326 // If the current font requests subpixel AA, force it to gray since we don't
1327 // allow subpixel AA.
1328 if (!mPermitSubpixelAA && newAA == CAIRO_ANTIALIAS_SUBPIXEL) {
1329 newAA = CAIRO_ANTIALIAS_GRAY;
1331 // Only override old AA with lower levels of AA.
1332 if (oldAA == CAIRO_ANTIALIAS_DEFAULT || (int)newAA < (int)oldAA) {
1333 cairo_font_options_set_antialias(mFontOptions, newAA);
1334 cairo_set_font_options(mContext, mFontOptions);
1338 void DrawTargetCairo::SetPermitSubpixelAA(bool aPermitSubpixelAA) {
1339 DrawTarget::SetPermitSubpixelAA(aPermitSubpixelAA);
1340 cairo_surface_set_subpixel_antialiasing(
1341 cairo_get_group_target(mContext),
1342 aPermitSubpixelAA ? CAIRO_SUBPIXEL_ANTIALIASING_ENABLED
1343 : CAIRO_SUBPIXEL_ANTIALIASING_DISABLED);
1346 static bool SupportsVariationSettings(cairo_surface_t* surface) {
1347 switch (cairo_surface_get_type(surface)) {
1348 case CAIRO_SURFACE_TYPE_PDF:
1349 case CAIRO_SURFACE_TYPE_PS:
1350 return false;
1351 default:
1352 return true;
1356 void DrawTargetCairo::FillGlyphs(ScaledFont* aFont, const GlyphBuffer& aBuffer,
1357 const Pattern& aPattern,
1358 const DrawOptions& aOptions) {
1359 if (mTransformSingular) {
1360 return;
1363 if (!IsValid()) {
1364 gfxDebug() << "FillGlyphs bad surface "
1365 << cairo_surface_status(cairo_get_group_target(mContext));
1366 return;
1369 cairo_scaled_font_t* cairoScaledFont =
1370 aFont ? aFont->GetCairoScaledFont() : nullptr;
1371 if (!cairoScaledFont) {
1372 gfxDevCrash(LogReason::InvalidFont) << "Invalid scaled font";
1373 return;
1376 AutoPrepareForDrawing prep(this, mContext);
1377 AutoClearDeviceOffset clear(aPattern);
1379 cairo_set_scaled_font(mContext, cairoScaledFont);
1381 cairo_pattern_t* pat =
1382 GfxPatternToCairoPattern(aPattern, aOptions.mAlpha, GetTransform());
1383 if (!pat) return;
1385 cairo_set_source(mContext, pat);
1386 cairo_pattern_destroy(pat);
1388 cairo_antialias_t aa = GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode);
1389 cairo_set_antialias(mContext, aa);
1391 // Override any font-specific options as necessary.
1392 SetFontOptions(aa);
1394 // Convert our GlyphBuffer into a vector of Cairo glyphs. This code can
1395 // execute millions of times in short periods, so we want to avoid heap
1396 // allocation whenever possible. So we use an inline vector capacity of 1024
1397 // bytes (the maximum allowed by mozilla::Vector), which gives an inline
1398 // length of 1024 / 24 = 42 elements, which is enough to typically avoid heap
1399 // allocation in ~99% of cases.
1400 Vector<cairo_glyph_t, 1024 / sizeof(cairo_glyph_t)> glyphs;
1401 if (!glyphs.resizeUninitialized(aBuffer.mNumGlyphs)) {
1402 gfxDevCrash(LogReason::GlyphAllocFailedCairo) << "glyphs allocation failed";
1403 return;
1405 for (uint32_t i = 0; i < aBuffer.mNumGlyphs; ++i) {
1406 glyphs[i].index = aBuffer.mGlyphs[i].mIndex;
1407 glyphs[i].x = aBuffer.mGlyphs[i].mPosition.x;
1408 glyphs[i].y = aBuffer.mGlyphs[i].mPosition.y;
1411 if (!SupportsVariationSettings(mSurface) && aFont->HasVariationSettings() &&
1412 StaticPrefs::print_font_variations_as_paths()) {
1413 cairo_set_fill_rule(mContext, CAIRO_FILL_RULE_WINDING);
1414 cairo_new_path(mContext);
1415 cairo_glyph_path(mContext, &glyphs[0], aBuffer.mNumGlyphs);
1416 cairo_set_operator(mContext, CAIRO_OPERATOR_OVER);
1417 cairo_fill(mContext);
1418 } else {
1419 cairo_show_glyphs(mContext, &glyphs[0], aBuffer.mNumGlyphs);
1422 if (cairo_surface_status(cairo_get_group_target(mContext))) {
1423 gfxDebug() << "Ending FillGlyphs with a bad surface "
1424 << cairo_surface_status(cairo_get_group_target(mContext));
1428 void DrawTargetCairo::Mask(const Pattern& aSource, const Pattern& aMask,
1429 const DrawOptions& aOptions /* = DrawOptions() */) {
1430 if (mTransformSingular) {
1431 return;
1434 AutoPrepareForDrawing prep(this, mContext);
1435 AutoClearDeviceOffset clearSource(aSource);
1436 AutoClearDeviceOffset clearMask(aMask);
1438 cairo_set_antialias(mContext,
1439 GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
1441 cairo_pattern_t* source =
1442 GfxPatternToCairoPattern(aSource, aOptions.mAlpha, GetTransform());
1443 if (!source) {
1444 return;
1447 cairo_pattern_t* mask =
1448 GfxPatternToCairoPattern(aMask, aOptions.mAlpha, GetTransform());
1449 if (!mask) {
1450 cairo_pattern_destroy(source);
1451 return;
1454 if (cairo_pattern_status(source) || cairo_pattern_status(mask)) {
1455 cairo_pattern_destroy(source);
1456 cairo_pattern_destroy(mask);
1457 gfxWarning() << "Invalid pattern";
1458 return;
1461 cairo_set_source(mContext, source);
1462 cairo_set_operator(mContext, GfxOpToCairoOp(aOptions.mCompositionOp));
1463 cairo_mask(mContext, mask);
1465 cairo_pattern_destroy(mask);
1466 cairo_pattern_destroy(source);
1469 void DrawTargetCairo::MaskSurface(const Pattern& aSource, SourceSurface* aMask,
1470 Point aOffset, const DrawOptions& aOptions) {
1471 if (mTransformSingular) {
1472 return;
1475 AutoPrepareForDrawing prep(this, mContext);
1476 AutoClearDeviceOffset clearSource(aSource);
1477 AutoClearDeviceOffset clearMask(aMask);
1479 if (!PatternIsCompatible(aSource)) {
1480 return;
1483 cairo_set_antialias(mContext,
1484 GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
1486 cairo_pattern_t* pat =
1487 GfxPatternToCairoPattern(aSource, aOptions.mAlpha, GetTransform());
1488 if (!pat) {
1489 return;
1492 if (cairo_pattern_status(pat)) {
1493 cairo_pattern_destroy(pat);
1494 gfxWarning() << "Invalid pattern";
1495 return;
1498 cairo_set_source(mContext, pat);
1500 if (NeedIntermediateSurface(aSource, aOptions)) {
1501 cairo_push_group_with_content(mContext, CAIRO_CONTENT_COLOR_ALPHA);
1503 // Don't want operators to be applied twice
1504 cairo_set_operator(mContext, CAIRO_OPERATOR_OVER);
1506 // Now draw the content using the desired operator
1507 cairo_paint_with_alpha(mContext, aOptions.mAlpha);
1509 cairo_pop_group_to_source(mContext);
1512 cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(aMask);
1513 if (!surf) {
1514 cairo_pattern_destroy(pat);
1515 return;
1517 cairo_pattern_t* mask = cairo_pattern_create_for_surface(surf);
1518 cairo_matrix_t matrix;
1520 cairo_matrix_init_translate(&matrix, -aOffset.x - aMask->GetRect().x,
1521 -aOffset.y - aMask->GetRect().y);
1522 cairo_pattern_set_matrix(mask, &matrix);
1524 cairo_set_operator(mContext, GfxOpToCairoOp(aOptions.mCompositionOp));
1526 cairo_mask(mContext, mask);
1528 cairo_surface_destroy(surf);
1529 cairo_pattern_destroy(mask);
1530 cairo_pattern_destroy(pat);
1533 void DrawTargetCairo::PushClip(const Path* aPath) {
1534 if (aPath->GetBackendType() != BackendType::CAIRO) {
1535 return;
1538 WillChange(aPath);
1539 cairo_save(mContext);
1541 PathCairo* path =
1542 const_cast<PathCairo*>(static_cast<const PathCairo*>(aPath));
1544 if (mTransformSingular) {
1545 cairo_new_path(mContext);
1546 cairo_rectangle(mContext, 0, 0, 0, 0);
1547 } else {
1548 path->SetPathOnContext(mContext);
1550 cairo_clip_preserve(mContext);
1553 void DrawTargetCairo::PushClipRect(const Rect& aRect) {
1554 WillChange();
1555 cairo_save(mContext);
1557 cairo_new_path(mContext);
1558 if (mTransformSingular) {
1559 cairo_rectangle(mContext, 0, 0, 0, 0);
1560 } else {
1561 cairo_rectangle(mContext, aRect.X(), aRect.Y(), aRect.Width(),
1562 aRect.Height());
1564 cairo_clip_preserve(mContext);
1567 void DrawTargetCairo::PopClip() {
1568 // save/restore does not affect the path, so no need to call WillChange()
1570 // cairo_restore will restore the transform too and we don't want to do that
1571 // so we'll save it now and restore it after the cairo_restore
1572 cairo_matrix_t mat;
1573 cairo_get_matrix(mContext, &mat);
1575 cairo_restore(mContext);
1577 cairo_set_matrix(mContext, &mat);
1580 void DrawTargetCairo::PushLayer(bool aOpaque, Float aOpacity,
1581 SourceSurface* aMask,
1582 const Matrix& aMaskTransform,
1583 const IntRect& aBounds, bool aCopyBackground) {
1584 PushLayerWithBlend(aOpaque, aOpacity, aMask, aMaskTransform, aBounds,
1585 aCopyBackground, CompositionOp::OP_OVER);
1588 void DrawTargetCairo::PushLayerWithBlend(bool aOpaque, Float aOpacity,
1589 SourceSurface* aMask,
1590 const Matrix& aMaskTransform,
1591 const IntRect& aBounds,
1592 bool aCopyBackground,
1593 CompositionOp aCompositionOp) {
1594 cairo_content_t content = CAIRO_CONTENT_COLOR_ALPHA;
1596 if (mFormat == SurfaceFormat::A8) {
1597 content = CAIRO_CONTENT_ALPHA;
1598 } else if (aOpaque) {
1599 content = CAIRO_CONTENT_COLOR;
1602 if (aCopyBackground) {
1603 cairo_surface_t* source = cairo_get_group_target(mContext);
1604 cairo_push_group_with_content(mContext, content);
1605 cairo_surface_t* dest = cairo_get_group_target(mContext);
1606 cairo_t* ctx = cairo_create(dest);
1607 cairo_set_source_surface(ctx, source, 0, 0);
1608 cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
1609 cairo_paint(ctx);
1610 cairo_destroy(ctx);
1611 } else {
1612 cairo_push_group_with_content(mContext, content);
1615 PushedLayer layer(aOpacity, aCompositionOp, mPermitSubpixelAA);
1617 if (aMask) {
1618 cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(aMask);
1619 if (surf) {
1620 layer.mMaskPattern = cairo_pattern_create_for_surface(surf);
1621 Matrix maskTransform = aMaskTransform;
1622 maskTransform.PreTranslate(aMask->GetRect().X(), aMask->GetRect().Y());
1623 cairo_matrix_t mat;
1624 GfxMatrixToCairoMatrix(maskTransform, mat);
1625 cairo_matrix_invert(&mat);
1626 cairo_pattern_set_matrix(layer.mMaskPattern, &mat);
1627 cairo_surface_destroy(surf);
1628 } else {
1629 gfxCriticalError() << "Failed to get cairo surface for mask surface!";
1633 mPushedLayers.push_back(layer);
1635 SetPermitSubpixelAA(aOpaque);
1638 void DrawTargetCairo::PopLayer() {
1639 MOZ_RELEASE_ASSERT(!mPushedLayers.empty());
1641 cairo_set_operator(mContext, CAIRO_OPERATOR_OVER);
1643 cairo_pop_group_to_source(mContext);
1645 PushedLayer layer = mPushedLayers.back();
1646 mPushedLayers.pop_back();
1648 if (!layer.mMaskPattern) {
1649 cairo_set_operator(mContext, GfxOpToCairoOp(layer.mCompositionOp));
1650 cairo_paint_with_alpha(mContext, layer.mOpacity);
1651 } else {
1652 if (layer.mOpacity != Float(1.0)) {
1653 cairo_push_group_with_content(mContext, CAIRO_CONTENT_COLOR_ALPHA);
1655 // Now draw the content using the desired operator
1656 cairo_paint_with_alpha(mContext, layer.mOpacity);
1658 cairo_pop_group_to_source(mContext);
1660 cairo_set_operator(mContext, GfxOpToCairoOp(layer.mCompositionOp));
1661 cairo_mask(mContext, layer.mMaskPattern);
1664 cairo_matrix_t mat;
1665 GfxMatrixToCairoMatrix(mTransform, mat);
1666 cairo_set_matrix(mContext, &mat);
1668 cairo_set_operator(mContext, CAIRO_OPERATOR_OVER);
1670 cairo_pattern_destroy(layer.mMaskPattern);
1671 SetPermitSubpixelAA(layer.mWasPermittingSubpixelAA);
1674 void DrawTargetCairo::ClearSurfaceForUnboundedSource(
1675 const CompositionOp& aOperator) {
1676 if (aOperator != CompositionOp::OP_SOURCE) return;
1677 cairo_set_operator(mContext, CAIRO_OPERATOR_CLEAR);
1678 // It doesn't really matter what the source is here, since Paint
1679 // isn't bounded by the source and the mask covers the entire clip
1680 // region.
1681 cairo_paint(mContext);
1684 already_AddRefed<GradientStops> DrawTargetCairo::CreateGradientStops(
1685 GradientStop* aStops, uint32_t aNumStops, ExtendMode aExtendMode) const {
1686 return MakeAndAddRef<GradientStopsCairo>(aStops, aNumStops, aExtendMode);
1689 already_AddRefed<FilterNode> DrawTargetCairo::CreateFilter(FilterType aType) {
1690 return FilterNodeSoftware::Create(aType);
1693 already_AddRefed<SourceSurface> DrawTargetCairo::CreateSourceSurfaceFromData(
1694 unsigned char* aData, const IntSize& aSize, int32_t aStride,
1695 SurfaceFormat aFormat) const {
1696 if (!aData) {
1697 gfxWarning() << "DrawTargetCairo::CreateSourceSurfaceFromData null aData";
1698 return nullptr;
1701 cairo_surface_t* surf =
1702 CopyToImageSurface(aData, IntRect(IntPoint(), aSize), aStride, aFormat);
1703 if (!surf) {
1704 return nullptr;
1707 RefPtr<SourceSurfaceCairo> source_surf =
1708 new SourceSurfaceCairo(surf, aSize, aFormat);
1709 cairo_surface_destroy(surf);
1711 return source_surf.forget();
1714 already_AddRefed<SourceSurface> DrawTargetCairo::OptimizeSourceSurface(
1715 SourceSurface* aSurface) const {
1716 RefPtr<SourceSurface> surface(aSurface);
1717 return surface.forget();
1720 already_AddRefed<SourceSurface>
1721 DrawTargetCairo::CreateSourceSurfaceFromNativeSurface(
1722 const NativeSurface& aSurface) const {
1723 return nullptr;
1726 already_AddRefed<DrawTarget> DrawTargetCairo::CreateSimilarDrawTarget(
1727 const IntSize& aSize, SurfaceFormat aFormat) const {
1728 if (cairo_surface_status(cairo_get_group_target(mContext))) {
1729 RefPtr<DrawTargetCairo> target = new DrawTargetCairo();
1730 if (target->Init(aSize, aFormat)) {
1731 return target.forget();
1735 cairo_surface_t* similar;
1736 switch (cairo_surface_get_type(mSurface)) {
1737 #ifdef CAIRO_HAS_WIN32_SURFACE
1738 case CAIRO_SURFACE_TYPE_WIN32:
1739 similar = cairo_win32_surface_create_with_dib(
1740 GfxFormatToCairoFormat(aFormat), aSize.width, aSize.height);
1741 break;
1742 #endif
1743 #ifdef CAIRO_HAS_QUARTZ_SURFACE
1744 case CAIRO_SURFACE_TYPE_QUARTZ:
1745 if (StaticPrefs::gfx_cairo_quartz_cg_layer_enabled()) {
1746 similar = cairo_quartz_surface_create_cg_layer(
1747 mSurface, GfxFormatToCairoContent(aFormat), aSize.width,
1748 aSize.height);
1749 break;
1751 [[fallthrough]];
1752 #endif
1753 default:
1754 similar = cairo_surface_create_similar(mSurface,
1755 GfxFormatToCairoContent(aFormat),
1756 aSize.width, aSize.height);
1757 break;
1760 if (!cairo_surface_status(similar)) {
1761 RefPtr<DrawTargetCairo> target = new DrawTargetCairo();
1762 if (target->InitAlreadyReferenced(similar, aSize)) {
1763 return target.forget();
1767 gfxCriticalError(
1768 CriticalLog::DefaultOptions(Factory::ReasonableSurfaceSize(aSize)))
1769 << "Failed to create similar cairo surface! Size: " << aSize
1770 << " Status: " << cairo_surface_status(similar)
1771 << cairo_surface_status(cairo_get_group_target(mContext)) << " format "
1772 << (int)aFormat;
1773 cairo_surface_destroy(similar);
1775 return nullptr;
1778 RefPtr<DrawTarget> DrawTargetCairo::CreateClippedDrawTarget(
1779 const Rect& aBounds, SurfaceFormat aFormat) {
1780 RefPtr<DrawTarget> result;
1781 // Doing this save()/restore() dance is wasteful
1782 cairo_save(mContext);
1784 if (!aBounds.IsEmpty()) {
1785 cairo_new_path(mContext);
1786 cairo_rectangle(mContext, aBounds.X(), aBounds.Y(), aBounds.Width(),
1787 aBounds.Height());
1788 cairo_clip(mContext);
1790 cairo_identity_matrix(mContext);
1791 IntRect clipBounds = IntRect::RoundOut(GetUserSpaceClip());
1792 if (!clipBounds.IsEmpty()) {
1793 RefPtr<DrawTarget> dt = CreateSimilarDrawTarget(
1794 IntSize(clipBounds.width, clipBounds.height), aFormat);
1795 if (dt) {
1796 result = gfx::Factory::CreateOffsetDrawTarget(
1797 dt, IntPoint(clipBounds.x, clipBounds.y));
1798 if (result) {
1799 result->SetTransform(mTransform);
1802 } else {
1803 // Everything is clipped but we still want some kind of surface
1804 result = CreateSimilarDrawTarget(IntSize(1, 1), aFormat);
1807 cairo_restore(mContext);
1808 return result;
1810 bool DrawTargetCairo::InitAlreadyReferenced(cairo_surface_t* aSurface,
1811 const IntSize& aSize,
1812 SurfaceFormat* aFormat) {
1813 if (cairo_surface_status(aSurface)) {
1814 gfxCriticalNote << "Attempt to create DrawTarget for invalid surface. "
1815 << aSize
1816 << " Cairo Status: " << cairo_surface_status(aSurface);
1817 cairo_surface_destroy(aSurface);
1818 return false;
1821 mContext = cairo_create(aSurface);
1822 mSurface = aSurface;
1823 mSize = aSize;
1824 mFormat = aFormat ? *aFormat : GfxFormatForCairoSurface(aSurface);
1826 // Cairo image surface have a bug where they will allocate a mask surface (for
1827 // clipping) the size of the clip extents, and don't take the surface extents
1828 // into account. Add a manual clip to the surface extents to prevent this.
1829 cairo_new_path(mContext);
1830 cairo_rectangle(mContext, 0, 0, mSize.width, mSize.height);
1831 cairo_clip(mContext);
1833 if (mFormat == SurfaceFormat::A8R8G8B8_UINT32 ||
1834 mFormat == SurfaceFormat::R8G8B8A8) {
1835 SetPermitSubpixelAA(false);
1836 } else {
1837 SetPermitSubpixelAA(true);
1840 return true;
1843 already_AddRefed<DrawTarget> DrawTargetCairo::CreateShadowDrawTarget(
1844 const IntSize& aSize, SurfaceFormat aFormat, float aSigma) const {
1845 cairo_surface_t* similar = cairo_surface_create_similar(
1846 cairo_get_target(mContext), GfxFormatToCairoContent(aFormat), aSize.width,
1847 aSize.height);
1849 if (cairo_surface_status(similar)) {
1850 return nullptr;
1853 // If we don't have a blur then we can use the RGBA mask and keep all the
1854 // operations in graphics memory.
1855 if (aSigma == 0.0f || aFormat == SurfaceFormat::A8) {
1856 RefPtr<DrawTargetCairo> target = new DrawTargetCairo();
1857 if (target->InitAlreadyReferenced(similar, aSize)) {
1858 return target.forget();
1859 } else {
1860 return nullptr;
1864 cairo_surface_t* blursurf =
1865 cairo_image_surface_create(CAIRO_FORMAT_A8, aSize.width, aSize.height);
1867 if (cairo_surface_status(blursurf)) {
1868 return nullptr;
1871 cairo_surface_t* tee = cairo_tee_surface_create(blursurf);
1872 cairo_surface_destroy(blursurf);
1873 if (cairo_surface_status(tee)) {
1874 cairo_surface_destroy(similar);
1875 return nullptr;
1878 cairo_tee_surface_add(tee, similar);
1879 cairo_surface_destroy(similar);
1881 RefPtr<DrawTargetCairo> target = new DrawTargetCairo();
1882 if (target->InitAlreadyReferenced(tee, aSize)) {
1883 return target.forget();
1885 return nullptr;
1888 bool DrawTargetCairo::Draw3DTransformedSurface(SourceSurface* aSurface,
1889 const Matrix4x4& aMatrix) {
1890 return DrawTarget::Draw3DTransformedSurface(aSurface, aMatrix);
1893 bool DrawTargetCairo::Init(cairo_surface_t* aSurface, const IntSize& aSize,
1894 SurfaceFormat* aFormat) {
1895 cairo_surface_reference(aSurface);
1896 return InitAlreadyReferenced(aSurface, aSize, aFormat);
1899 bool DrawTargetCairo::Init(const IntSize& aSize, SurfaceFormat aFormat) {
1900 cairo_surface_t* surf = cairo_image_surface_create(
1901 GfxFormatToCairoFormat(aFormat), aSize.width, aSize.height);
1902 return InitAlreadyReferenced(surf, aSize);
1905 bool DrawTargetCairo::Init(unsigned char* aData, const IntSize& aSize,
1906 int32_t aStride, SurfaceFormat aFormat) {
1907 cairo_surface_t* surf = cairo_image_surface_create_for_data(
1908 aData, GfxFormatToCairoFormat(aFormat), aSize.width, aSize.height,
1909 aStride);
1910 return InitAlreadyReferenced(surf, aSize);
1913 void* DrawTargetCairo::GetNativeSurface(NativeSurfaceType aType) {
1914 if (aType == NativeSurfaceType::CAIRO_CONTEXT) {
1915 return mContext;
1918 return nullptr;
1921 void DrawTargetCairo::MarkSnapshotIndependent() {
1922 if (mSnapshot) {
1923 if (mSnapshot->refCount() > 1) {
1924 // We only need to worry about snapshots that someone else knows about
1925 mSnapshot->DrawTargetWillChange();
1927 mSnapshot = nullptr;
1931 void DrawTargetCairo::WillChange(const Path* aPath /* = nullptr */) {
1932 MarkSnapshotIndependent();
1933 MOZ_ASSERT(!mLockedBits);
1936 void DrawTargetCairo::SetTransform(const Matrix& aTransform) {
1937 DrawTarget::SetTransform(aTransform);
1939 mTransformSingular = aTransform.IsSingular();
1940 if (!mTransformSingular) {
1941 cairo_matrix_t mat;
1942 GfxMatrixToCairoMatrix(mTransform, mat);
1943 cairo_set_matrix(mContext, &mat);
1947 Rect DrawTargetCairo::GetUserSpaceClip() const {
1948 double clipX1, clipY1, clipX2, clipY2;
1949 cairo_clip_extents(mContext, &clipX1, &clipY1, &clipX2, &clipY2);
1950 return Rect(clipX1, clipY1, clipX2 - clipX1,
1951 clipY2 - clipY1); // Narrowing of doubles to floats
1954 #ifdef MOZ_X11
1955 bool BorrowedXlibDrawable::Init(DrawTarget* aDT) {
1956 MOZ_ASSERT(aDT, "Caller should check for nullptr");
1957 MOZ_ASSERT(!mDT, "Can't initialize twice!");
1958 mDT = aDT;
1959 mDrawable = X11None;
1961 # ifdef CAIRO_HAS_XLIB_SURFACE
1962 if (aDT->GetBackendType() != BackendType::CAIRO || aDT->IsTiledDrawTarget()) {
1963 return false;
1966 DrawTargetCairo* cairoDT = static_cast<DrawTargetCairo*>(aDT);
1967 cairo_surface_t* surf = cairo_get_group_target(cairoDT->mContext);
1968 if (cairo_surface_get_type(surf) != CAIRO_SURFACE_TYPE_XLIB) {
1969 return false;
1971 cairo_surface_flush(surf);
1973 cairoDT->WillChange();
1975 mDisplay = cairo_xlib_surface_get_display(surf);
1976 mDrawable = cairo_xlib_surface_get_drawable(surf);
1977 mScreen = cairo_xlib_surface_get_screen(surf);
1978 mVisual = cairo_xlib_surface_get_visual(surf);
1979 mSize.width = cairo_xlib_surface_get_width(surf);
1980 mSize.height = cairo_xlib_surface_get_height(surf);
1982 double x = 0, y = 0;
1983 cairo_surface_get_device_offset(surf, &x, &y);
1984 mOffset = Point(x, y);
1986 return true;
1987 # else
1988 return false;
1989 # endif
1992 void BorrowedXlibDrawable::Finish() {
1993 DrawTargetCairo* cairoDT = static_cast<DrawTargetCairo*>(mDT);
1994 cairo_surface_t* surf = cairo_get_group_target(cairoDT->mContext);
1995 cairo_surface_mark_dirty(surf);
1996 if (mDrawable) {
1997 mDrawable = X11None;
2000 #endif
2002 } // namespace gfx
2003 } // namespace mozilla