gfx/thebes/gfxASurface.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/gfx/thebes/gfxASurface.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,939 @@
     1.4 +/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
     1.5 + * This Source Code Form is subject to the terms of the Mozilla Public
     1.6 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.7 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.8 +
     1.9 +#include "nsIMemoryReporter.h"
    1.10 +#include "nsMemory.h"
    1.11 +#include "mozilla/ArrayUtils.h"
    1.12 +#include "mozilla/Base64.h"
    1.13 +#include "mozilla/CheckedInt.h"
    1.14 +#include "mozilla/Attributes.h"
    1.15 +#include "mozilla/MemoryReporting.h"
    1.16 +#include "nsISupportsImpl.h"
    1.17 +#include "mozilla/gfx/2D.h"
    1.18 +#include "gfx2DGlue.h"
    1.19 +
    1.20 +#include "gfxASurface.h"
    1.21 +#include "gfxContext.h"
    1.22 +#include "gfxImageSurface.h"
    1.23 +#include "gfxPlatform.h"
    1.24 +#include "gfxRect.h"
    1.25 +
    1.26 +#include "cairo.h"
    1.27 +#include <algorithm>
    1.28 +
    1.29 +#ifdef CAIRO_HAS_WIN32_SURFACE
    1.30 +#include "gfxWindowsSurface.h"
    1.31 +#endif
    1.32 +#ifdef CAIRO_HAS_D2D_SURFACE
    1.33 +#include "gfxD2DSurface.h"
    1.34 +#endif
    1.35 +
    1.36 +#ifdef MOZ_X11
    1.37 +#include "gfxXlibSurface.h"
    1.38 +#endif
    1.39 +
    1.40 +#ifdef CAIRO_HAS_QUARTZ_SURFACE
    1.41 +#include "gfxQuartzSurface.h"
    1.42 +#include "gfxQuartzImageSurface.h"
    1.43 +#endif
    1.44 +
    1.45 +#if defined(CAIRO_HAS_QT_SURFACE) && defined(MOZ_WIDGET_QT)
    1.46 +#include "gfxQPainterSurface.h"
    1.47 +#endif
    1.48 +
    1.49 +#include <stdio.h>
    1.50 +#include <limits.h>
    1.51 +
    1.52 +#include "imgIEncoder.h"
    1.53 +#include "nsComponentManagerUtils.h"
    1.54 +#include "nsISupportsUtils.h"
    1.55 +#include "nsCOMPtr.h"
    1.56 +#include "nsServiceManagerUtils.h"
    1.57 +#include "nsString.h"
    1.58 +#include "nsIClipboardHelper.h"
    1.59 +
    1.60 +using namespace mozilla;
    1.61 +using namespace mozilla::gfx;
    1.62 +
    1.63 +static cairo_user_data_key_t gfxasurface_pointer_key;
    1.64 +
    1.65 +gfxASurface::gfxASurface()
    1.66 + : mSurface(nullptr), mFloatingRefs(0), mBytesRecorded(0),
    1.67 +   mSurfaceValid(false), mAllowUseAsSource(true)
    1.68 +{
    1.69 +    MOZ_COUNT_CTOR(gfxASurface);
    1.70 +}
    1.71 +
    1.72 +gfxASurface::~gfxASurface()
    1.73 +{
    1.74 +    RecordMemoryFreed();
    1.75 +
    1.76 +    MOZ_COUNT_DTOR(gfxASurface);
    1.77 +}
    1.78 +
    1.79 +// Surfaces use refcounting that's tied to the cairo surface refcnt, to avoid
    1.80 +// refcount mismatch issues.
    1.81 +nsrefcnt
    1.82 +gfxASurface::AddRef(void)
    1.83 +{
    1.84 +    if (mSurfaceValid) {
    1.85 +        if (mFloatingRefs) {
    1.86 +            // eat a floating ref
    1.87 +            mFloatingRefs--;
    1.88 +        } else {
    1.89 +            cairo_surface_reference(mSurface);
    1.90 +        }
    1.91 +
    1.92 +        return (nsrefcnt) cairo_surface_get_reference_count(mSurface);
    1.93 +    } else {
    1.94 +        // the surface isn't valid, but we still need to refcount
    1.95 +        // the gfxASurface
    1.96 +        return ++mFloatingRefs;
    1.97 +    }
    1.98 +}
    1.99 +
   1.100 +nsrefcnt
   1.101 +gfxASurface::Release(void)
   1.102 +{
   1.103 +    if (mSurfaceValid) {
   1.104 +        NS_ASSERTION(mFloatingRefs == 0, "gfxASurface::Release with floating refs still hanging around!");
   1.105 +
   1.106 +        // Note that there is a destructor set on user data for mSurface,
   1.107 +        // which will delete this gfxASurface wrapper when the surface's refcount goes
   1.108 +        // out of scope.
   1.109 +        nsrefcnt refcnt = (nsrefcnt) cairo_surface_get_reference_count(mSurface);
   1.110 +        cairo_surface_destroy(mSurface);
   1.111 +
   1.112 +        // |this| may not be valid any more, don't use it!
   1.113 +
   1.114 +        return --refcnt;
   1.115 +    } else {
   1.116 +        if (--mFloatingRefs == 0) {
   1.117 +            delete this;
   1.118 +            return 0;
   1.119 +        }
   1.120 +
   1.121 +        return mFloatingRefs;
   1.122 +    }
   1.123 +}
   1.124 +
   1.125 +nsrefcnt
   1.126 +gfxASurface::AddRefExternal(void)
   1.127 +{
   1.128 +  return AddRef();
   1.129 +}
   1.130 +
   1.131 +nsrefcnt
   1.132 +gfxASurface::ReleaseExternal(void)
   1.133 +{
   1.134 +  return Release();
   1.135 +}
   1.136 +
   1.137 +void
   1.138 +gfxASurface::SurfaceDestroyFunc(void *data) {
   1.139 +    gfxASurface *surf = (gfxASurface*) data;
   1.140 +    // fprintf (stderr, "Deleting wrapper for %p (wrapper: %p)\n", surf->mSurface, data);
   1.141 +    delete surf;
   1.142 +}
   1.143 +
   1.144 +gfxASurface*
   1.145 +gfxASurface::GetSurfaceWrapper(cairo_surface_t *csurf)
   1.146 +{
   1.147 +    if (!csurf)
   1.148 +        return nullptr;
   1.149 +    return (gfxASurface*) cairo_surface_get_user_data(csurf, &gfxasurface_pointer_key);
   1.150 +}
   1.151 +
   1.152 +void
   1.153 +gfxASurface::SetSurfaceWrapper(cairo_surface_t *csurf, gfxASurface *asurf)
   1.154 +{
   1.155 +    if (!csurf)
   1.156 +        return;
   1.157 +    cairo_surface_set_user_data(csurf, &gfxasurface_pointer_key, asurf, SurfaceDestroyFunc);
   1.158 +}
   1.159 +
   1.160 +already_AddRefed<gfxASurface>
   1.161 +gfxASurface::Wrap (cairo_surface_t *csurf, const gfxIntSize& aSize)
   1.162 +{
   1.163 +    nsRefPtr<gfxASurface> result;
   1.164 +
   1.165 +    /* Do we already have a wrapper for this surface? */
   1.166 +    result = GetSurfaceWrapper(csurf);
   1.167 +    if (result) {
   1.168 +        // fprintf(stderr, "Existing wrapper for %p -> %p\n", csurf, result);
   1.169 +        return result.forget();
   1.170 +    }
   1.171 +
   1.172 +    /* No wrapper; figure out the surface type and create it */
   1.173 +    cairo_surface_type_t stype = cairo_surface_get_type(csurf);
   1.174 +
   1.175 +    if (stype == CAIRO_SURFACE_TYPE_IMAGE) {
   1.176 +        result = new gfxImageSurface(csurf);
   1.177 +    }
   1.178 +#ifdef CAIRO_HAS_WIN32_SURFACE
   1.179 +    else if (stype == CAIRO_SURFACE_TYPE_WIN32 ||
   1.180 +             stype == CAIRO_SURFACE_TYPE_WIN32_PRINTING) {
   1.181 +        result = new gfxWindowsSurface(csurf);
   1.182 +    }
   1.183 +#endif
   1.184 +#ifdef CAIRO_HAS_D2D_SURFACE
   1.185 +    else if (stype == CAIRO_SURFACE_TYPE_D2D) {
   1.186 +        result = new gfxD2DSurface(csurf);
   1.187 +    }
   1.188 +#endif
   1.189 +#ifdef MOZ_X11
   1.190 +    else if (stype == CAIRO_SURFACE_TYPE_XLIB) {
   1.191 +        result = new gfxXlibSurface(csurf);
   1.192 +    }
   1.193 +#endif
   1.194 +#ifdef CAIRO_HAS_QUARTZ_SURFACE
   1.195 +    else if (stype == CAIRO_SURFACE_TYPE_QUARTZ) {
   1.196 +        result = new gfxQuartzSurface(csurf, aSize);
   1.197 +    }
   1.198 +    else if (stype == CAIRO_SURFACE_TYPE_QUARTZ_IMAGE) {
   1.199 +        result = new gfxQuartzImageSurface(csurf);
   1.200 +    }
   1.201 +#endif
   1.202 +#if defined(CAIRO_HAS_QT_SURFACE) && defined(MOZ_WIDGET_QT)
   1.203 +    else if (stype == CAIRO_SURFACE_TYPE_QT) {
   1.204 +        result = new gfxQPainterSurface(csurf);
   1.205 +    }
   1.206 +#endif
   1.207 +    else {
   1.208 +        result = new gfxUnknownSurface(csurf, aSize);
   1.209 +    }
   1.210 +
   1.211 +    // fprintf(stderr, "New wrapper for %p -> %p\n", csurf, result);
   1.212 +
   1.213 +    return result.forget();
   1.214 +}
   1.215 +
   1.216 +void
   1.217 +gfxASurface::Init(cairo_surface_t* surface, bool existingSurface)
   1.218 +{
   1.219 +    SetSurfaceWrapper(surface, this);
   1.220 +
   1.221 +    mSurface = surface;
   1.222 +    mSurfaceValid = surface && !cairo_surface_status(surface);
   1.223 +
   1.224 +    if (existingSurface || !mSurfaceValid) {
   1.225 +        mFloatingRefs = 0;
   1.226 +    } else {
   1.227 +        mFloatingRefs = 1;
   1.228 +#ifdef MOZ_TREE_CAIRO
   1.229 +        if (cairo_surface_get_content(surface) != CAIRO_CONTENT_COLOR) {
   1.230 +            cairo_surface_set_subpixel_antialiasing(surface, CAIRO_SUBPIXEL_ANTIALIASING_DISABLED);
   1.231 +        }
   1.232 +#endif
   1.233 +    }
   1.234 +}
   1.235 +
   1.236 +gfxSurfaceType
   1.237 +gfxASurface::GetType() const
   1.238 +{
   1.239 +    if (!mSurfaceValid)
   1.240 +        return (gfxSurfaceType)-1;
   1.241 +
   1.242 +    return (gfxSurfaceType)cairo_surface_get_type(mSurface);
   1.243 +}
   1.244 +
   1.245 +gfxContentType
   1.246 +gfxASurface::GetContentType() const
   1.247 +{
   1.248 +    if (!mSurfaceValid)
   1.249 +        return (gfxContentType)-1;
   1.250 +
   1.251 +    return (gfxContentType)cairo_surface_get_content(mSurface);
   1.252 +}
   1.253 +
   1.254 +void
   1.255 +gfxASurface::SetDeviceOffset(const gfxPoint& offset)
   1.256 +{
   1.257 +    if (!mSurfaceValid)
   1.258 +        return;
   1.259 +    cairo_surface_set_device_offset(mSurface,
   1.260 +                                    offset.x, offset.y);
   1.261 +}
   1.262 +
   1.263 +gfxPoint
   1.264 +gfxASurface::GetDeviceOffset() const
   1.265 +{
   1.266 +    if (!mSurfaceValid)
   1.267 +        return gfxPoint(0.0, 0.0);
   1.268 +    gfxPoint pt;
   1.269 +    cairo_surface_get_device_offset(mSurface, &pt.x, &pt.y);
   1.270 +    return pt;
   1.271 +}
   1.272 +
   1.273 +void
   1.274 +gfxASurface::Flush() const
   1.275 +{
   1.276 +    if (!mSurfaceValid)
   1.277 +        return;
   1.278 +    cairo_surface_flush(mSurface);
   1.279 +    gfxPlatform::ClearSourceSurfaceForSurface(const_cast<gfxASurface*>(this));
   1.280 +}
   1.281 +
   1.282 +void
   1.283 +gfxASurface::MarkDirty()
   1.284 +{
   1.285 +    if (!mSurfaceValid)
   1.286 +        return;
   1.287 +    cairo_surface_mark_dirty(mSurface);
   1.288 +    gfxPlatform::ClearSourceSurfaceForSurface(this);
   1.289 +}
   1.290 +
   1.291 +void
   1.292 +gfxASurface::MarkDirty(const gfxRect& r)
   1.293 +{
   1.294 +    if (!mSurfaceValid)
   1.295 +        return;
   1.296 +    cairo_surface_mark_dirty_rectangle(mSurface,
   1.297 +                                       (int) r.X(), (int) r.Y(),
   1.298 +                                       (int) r.Width(), (int) r.Height());
   1.299 +    gfxPlatform::ClearSourceSurfaceForSurface(this);
   1.300 +}
   1.301 +
   1.302 +void
   1.303 +gfxASurface::SetData(const cairo_user_data_key_t *key,
   1.304 +                     void *user_data,
   1.305 +                     thebes_destroy_func_t destroy)
   1.306 +{
   1.307 +    if (!mSurfaceValid)
   1.308 +        return;
   1.309 +    cairo_surface_set_user_data(mSurface, key, user_data, destroy);
   1.310 +}
   1.311 +
   1.312 +void *
   1.313 +gfxASurface::GetData(const cairo_user_data_key_t *key)
   1.314 +{
   1.315 +    if (!mSurfaceValid)
   1.316 +        return nullptr;
   1.317 +    return cairo_surface_get_user_data(mSurface, key);
   1.318 +}
   1.319 +
   1.320 +void
   1.321 +gfxASurface::Finish()
   1.322 +{
   1.323 +    // null surfaces are allowed here
   1.324 +    cairo_surface_finish(mSurface);
   1.325 +}
   1.326 +
   1.327 +already_AddRefed<gfxASurface>
   1.328 +gfxASurface::CreateSimilarSurface(gfxContentType aContent,
   1.329 +                                  const nsIntSize& aSize)
   1.330 +{
   1.331 +    if (!mSurface || !mSurfaceValid) {
   1.332 +      return nullptr;
   1.333 +    }
   1.334 +    
   1.335 +    cairo_surface_t *surface =
   1.336 +        cairo_surface_create_similar(mSurface, cairo_content_t(int(aContent)),
   1.337 +                                     aSize.width, aSize.height);
   1.338 +    if (cairo_surface_status(surface)) {
   1.339 +        cairo_surface_destroy(surface);
   1.340 +        return nullptr;
   1.341 +    }
   1.342 +
   1.343 +    nsRefPtr<gfxASurface> result = Wrap(surface, aSize);
   1.344 +    cairo_surface_destroy(surface);
   1.345 +    return result.forget();
   1.346 +}
   1.347 +
   1.348 +already_AddRefed<gfxImageSurface>
   1.349 +gfxASurface::GetAsReadableARGB32ImageSurface()
   1.350 +{
   1.351 +    nsRefPtr<gfxImageSurface> imgSurface = GetAsImageSurface();
   1.352 +    if (!imgSurface || imgSurface->Format() != gfxImageFormat::ARGB32) {
   1.353 +      imgSurface = CopyToARGB32ImageSurface();
   1.354 +    }
   1.355 +    return imgSurface.forget();
   1.356 +}
   1.357 +
   1.358 +already_AddRefed<gfxImageSurface>
   1.359 +gfxASurface::CopyToARGB32ImageSurface()
   1.360 +{
   1.361 +    if (!mSurface || !mSurfaceValid) {
   1.362 +      return nullptr;
   1.363 +    }
   1.364 +
   1.365 +    const nsIntSize size = GetSize();
   1.366 +    nsRefPtr<gfxImageSurface> imgSurface =
   1.367 +        new gfxImageSurface(size, gfxImageFormat::ARGB32);
   1.368 +
   1.369 +    RefPtr<DrawTarget> dt = gfxPlatform::GetPlatform()->CreateDrawTargetForSurface(imgSurface, IntSize(size.width, size.height));
   1.370 +    RefPtr<SourceSurface> source = gfxPlatform::GetPlatform()->GetSourceSurfaceForSurface(dt, this);
   1.371 +
   1.372 +    dt->CopySurface(source, IntRect(0, 0, size.width, size.height), IntPoint());
   1.373 +
   1.374 +    return imgSurface.forget();
   1.375 +}
   1.376 +
   1.377 +int
   1.378 +gfxASurface::CairoStatus()
   1.379 +{
   1.380 +    if (!mSurfaceValid)
   1.381 +        return -1;
   1.382 +
   1.383 +    return cairo_surface_status(mSurface);
   1.384 +}
   1.385 +
   1.386 +/* static */
   1.387 +bool
   1.388 +gfxASurface::CheckSurfaceSize(const nsIntSize& sz, int32_t limit)
   1.389 +{
   1.390 +    if (sz.width < 0 || sz.height < 0) {
   1.391 +        NS_WARNING("Surface width or height < 0!");
   1.392 +        return false;
   1.393 +    }
   1.394 +
   1.395 +    // reject images with sides bigger than limit
   1.396 +    if (limit && (sz.width > limit || sz.height > limit)) {
   1.397 +        NS_WARNING("Surface size too large (exceeds caller's limit)!");
   1.398 +        return false;
   1.399 +    }
   1.400 +
   1.401 +#if defined(XP_MACOSX)
   1.402 +    // CoreGraphics is limited to images < 32K in *height*,
   1.403 +    // so clamp all surfaces on the Mac to that height
   1.404 +    if (sz.height > SHRT_MAX) {
   1.405 +        NS_WARNING("Surface size too large (exceeds CoreGraphics limit)!");
   1.406 +        return false;
   1.407 +    }
   1.408 +#endif
   1.409 +
   1.410 +    // make sure the surface area doesn't overflow a int32_t
   1.411 +    CheckedInt<int32_t> tmp = sz.width;
   1.412 +    tmp *= sz.height;
   1.413 +    if (!tmp.isValid()) {
   1.414 +        NS_WARNING("Surface size too large (would overflow)!");
   1.415 +        return false;
   1.416 +    }
   1.417 +
   1.418 +    // assuming 4-byte stride, make sure the allocation size
   1.419 +    // doesn't overflow a int32_t either
   1.420 +    tmp *= 4;
   1.421 +    if (!tmp.isValid()) {
   1.422 +        NS_WARNING("Allocation too large (would overflow)!");
   1.423 +        return false;
   1.424 +    }
   1.425 +
   1.426 +    return true;
   1.427 +}
   1.428 +
   1.429 +/* static */
   1.430 +int32_t
   1.431 +gfxASurface::FormatStrideForWidth(gfxImageFormat format, int32_t width)
   1.432 +{
   1.433 +    return cairo_format_stride_for_width((cairo_format_t)(int)format, (int)width);
   1.434 +}
   1.435 +
   1.436 +nsresult
   1.437 +gfxASurface::BeginPrinting(const nsAString& aTitle, const nsAString& aPrintToFileName)
   1.438 +{
   1.439 +    return NS_OK;
   1.440 +}
   1.441 +
   1.442 +nsresult
   1.443 +gfxASurface::EndPrinting()
   1.444 +{
   1.445 +    return NS_OK;
   1.446 +}
   1.447 +
   1.448 +nsresult
   1.449 +gfxASurface::AbortPrinting()
   1.450 +{
   1.451 +    return NS_OK;
   1.452 +}
   1.453 +
   1.454 +nsresult
   1.455 +gfxASurface::BeginPage()
   1.456 +{
   1.457 +    return NS_OK;
   1.458 +}
   1.459 +
   1.460 +nsresult
   1.461 +gfxASurface::EndPage()
   1.462 +{
   1.463 +    return NS_OK;
   1.464 +}
   1.465 +
   1.466 +gfxContentType
   1.467 +gfxASurface::ContentFromFormat(gfxImageFormat format)
   1.468 +{
   1.469 +    switch (format) {
   1.470 +        case gfxImageFormat::ARGB32:
   1.471 +            return gfxContentType::COLOR_ALPHA;
   1.472 +        case gfxImageFormat::RGB24:
   1.473 +        case gfxImageFormat::RGB16_565:
   1.474 +            return gfxContentType::COLOR;
   1.475 +        case gfxImageFormat::A8:
   1.476 +        case gfxImageFormat::A1:
   1.477 +            return gfxContentType::ALPHA;
   1.478 +
   1.479 +        case gfxImageFormat::Unknown:
   1.480 +        default:
   1.481 +            return gfxContentType::COLOR;
   1.482 +    }
   1.483 +}
   1.484 +
   1.485 +void
   1.486 +gfxASurface::SetSubpixelAntialiasingEnabled(bool aEnabled)
   1.487 +{
   1.488 +#ifdef MOZ_TREE_CAIRO
   1.489 +    if (!mSurfaceValid)
   1.490 +        return;
   1.491 +    cairo_surface_set_subpixel_antialiasing(mSurface,
   1.492 +        aEnabled ? CAIRO_SUBPIXEL_ANTIALIASING_ENABLED : CAIRO_SUBPIXEL_ANTIALIASING_DISABLED);
   1.493 +#endif
   1.494 +}
   1.495 +
   1.496 +bool
   1.497 +gfxASurface::GetSubpixelAntialiasingEnabled()
   1.498 +{
   1.499 +    if (!mSurfaceValid)
   1.500 +      return false;
   1.501 +#ifdef MOZ_TREE_CAIRO
   1.502 +    return cairo_surface_get_subpixel_antialiasing(mSurface) == CAIRO_SUBPIXEL_ANTIALIASING_ENABLED;
   1.503 +#else
   1.504 +    return true;
   1.505 +#endif
   1.506 +}
   1.507 +
   1.508 +gfxMemoryLocation
   1.509 +gfxASurface::GetMemoryLocation() const
   1.510 +{
   1.511 +    return gfxMemoryLocation::IN_PROCESS_HEAP;
   1.512 +}
   1.513 +
   1.514 +int32_t
   1.515 +gfxASurface::BytePerPixelFromFormat(gfxImageFormat format)
   1.516 +{
   1.517 +    switch (format) {
   1.518 +        case gfxImageFormat::ARGB32:
   1.519 +        case gfxImageFormat::RGB24:
   1.520 +            return 4;
   1.521 +        case gfxImageFormat::RGB16_565:
   1.522 +            return 2;
   1.523 +        case gfxImageFormat::A8:
   1.524 +            return 1;
   1.525 +        default:
   1.526 +            NS_WARNING("Unknown byte per pixel value for Image format");
   1.527 +    }
   1.528 +    return 0;
   1.529 +}
   1.530 +
   1.531 +void
   1.532 +gfxASurface::FastMovePixels(const nsIntRect& aSourceRect,
   1.533 +                            const nsIntPoint& aDestTopLeft)
   1.534 +{
   1.535 +    // Used when the backend can internally handle self copies.
   1.536 +    nsIntRect dest(aDestTopLeft, aSourceRect.Size());
   1.537 +    
   1.538 +    nsRefPtr<gfxContext> ctx = new gfxContext(this);
   1.539 +    ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
   1.540 +    nsIntPoint srcOrigin = dest.TopLeft() - aSourceRect.TopLeft();
   1.541 +    ctx->SetSource(this, gfxPoint(srcOrigin.x, srcOrigin.y));
   1.542 +    ctx->Rectangle(gfxRect(dest.x, dest.y, dest.width, dest.height));
   1.543 +    ctx->Fill();
   1.544 +}
   1.545 +
   1.546 +void
   1.547 +gfxASurface::MovePixels(const nsIntRect& aSourceRect,
   1.548 +                        const nsIntPoint& aDestTopLeft)
   1.549 +{
   1.550 +    // Assume the backend can't handle self copying well and allocate
   1.551 +    // a temporary surface instead.
   1.552 +    nsRefPtr<gfxASurface> tmp = 
   1.553 +      CreateSimilarSurface(GetContentType(), 
   1.554 +                           nsIntSize(aSourceRect.width, aSourceRect.height));
   1.555 +    // CreateSimilarSurface can return nullptr if the current surface is
   1.556 +    // in an error state. This isn't good, but its better to carry
   1.557 +    // on with the error surface instead of crashing.
   1.558 +    NS_WARN_IF_FALSE(tmp, "Must have temporary surface to move pixels!");
   1.559 +    if (!tmp) {
   1.560 +        return;
   1.561 +    }
   1.562 +    nsRefPtr<gfxContext> ctx = new gfxContext(tmp);
   1.563 +    ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
   1.564 +    ctx->SetSource(this, gfxPoint(-aSourceRect.x, -aSourceRect.y));
   1.565 +    ctx->Paint();
   1.566 +
   1.567 +    ctx = new gfxContext(this);
   1.568 +    ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
   1.569 +    ctx->SetSource(tmp, gfxPoint(aDestTopLeft.x, aDestTopLeft.y));
   1.570 +    ctx->Rectangle(gfxRect(aDestTopLeft.x, 
   1.571 +                           aDestTopLeft.y, 
   1.572 +                           aSourceRect.width, 
   1.573 +                           aSourceRect.height));
   1.574 +    ctx->Fill();
   1.575 +}
   1.576 +
   1.577 +/** Memory reporting **/
   1.578 +
   1.579 +static const char *sDefaultSurfaceDescription =
   1.580 +    "Memory used by gfx surface of the given type.";
   1.581 +
   1.582 +struct SurfaceMemoryReporterAttrs {
   1.583 +  const char *path;
   1.584 +  const char *description;
   1.585 +};
   1.586 +
   1.587 +static const SurfaceMemoryReporterAttrs sSurfaceMemoryReporterAttrs[] = {
   1.588 +    {"gfx-surface-image", nullptr},
   1.589 +    {"gfx-surface-pdf", nullptr},
   1.590 +    {"gfx-surface-ps", nullptr},
   1.591 +    {"gfx-surface-xlib",
   1.592 +     "Memory used by xlib surfaces to store pixmaps. This memory lives in "
   1.593 +     "the X server's process rather than in this application, so the bytes "
   1.594 +     "accounted for here aren't counted in vsize, resident, explicit, or any of "
   1.595 +     "the other measurements on this page."},
   1.596 +    {"gfx-surface-xcb", nullptr},
   1.597 +    {"gfx-surface-glitz???", nullptr},       // should never be used
   1.598 +    {"gfx-surface-quartz", nullptr},
   1.599 +    {"gfx-surface-win32", nullptr},
   1.600 +    {"gfx-surface-beos", nullptr},
   1.601 +    {"gfx-surface-directfb???", nullptr},    // should never be used
   1.602 +    {"gfx-surface-svg", nullptr},
   1.603 +    {"gfx-surface-os2", nullptr},
   1.604 +    {"gfx-surface-win32printing", nullptr},
   1.605 +    {"gfx-surface-quartzimage", nullptr},
   1.606 +    {"gfx-surface-script", nullptr},
   1.607 +    {"gfx-surface-qpainter", nullptr},
   1.608 +    {"gfx-surface-recording", nullptr},
   1.609 +    {"gfx-surface-vg", nullptr},
   1.610 +    {"gfx-surface-gl", nullptr},
   1.611 +    {"gfx-surface-drm", nullptr},
   1.612 +    {"gfx-surface-tee", nullptr},
   1.613 +    {"gfx-surface-xml", nullptr},
   1.614 +    {"gfx-surface-skia", nullptr},
   1.615 +    {"gfx-surface-subsurface", nullptr},
   1.616 +    {"gfx-surface-d2d", nullptr},
   1.617 +};
   1.618 +
   1.619 +PR_STATIC_ASSERT(MOZ_ARRAY_LENGTH(sSurfaceMemoryReporterAttrs) ==
   1.620 +                 size_t(gfxSurfaceType::Max));
   1.621 +#ifdef CAIRO_HAS_D2D_SURFACE
   1.622 +PR_STATIC_ASSERT(uint32_t(CAIRO_SURFACE_TYPE_D2D) ==
   1.623 +                 uint32_t(gfxSurfaceType::D2D));
   1.624 +#endif
   1.625 +PR_STATIC_ASSERT(uint32_t(CAIRO_SURFACE_TYPE_SKIA) ==
   1.626 +                 uint32_t(gfxSurfaceType::Skia));
   1.627 +
   1.628 +/* Surface size memory reporting */
   1.629 +
   1.630 +static int64_t gSurfaceMemoryUsed[size_t(gfxSurfaceType::Max)] = { 0 };
   1.631 +
   1.632 +class SurfaceMemoryReporter MOZ_FINAL : public nsIMemoryReporter
   1.633 +{
   1.634 +public:
   1.635 +    NS_DECL_ISUPPORTS
   1.636 +
   1.637 +    NS_IMETHOD CollectReports(nsIMemoryReporterCallback *aCb,
   1.638 +                              nsISupports *aClosure)
   1.639 +    {
   1.640 +        const size_t len = ArrayLength(sSurfaceMemoryReporterAttrs);
   1.641 +        for (size_t i = 0; i < len; i++) {
   1.642 +            int64_t amount = gSurfaceMemoryUsed[i];
   1.643 +
   1.644 +            if (amount != 0) {
   1.645 +                const char *path = sSurfaceMemoryReporterAttrs[i].path;
   1.646 +                const char *desc = sSurfaceMemoryReporterAttrs[i].description;
   1.647 +                if (!desc) {
   1.648 +                    desc = sDefaultSurfaceDescription;
   1.649 +                }
   1.650 +
   1.651 +                nsresult rv = aCb->Callback(EmptyCString(), nsCString(path),
   1.652 +                                            KIND_OTHER, UNITS_BYTES,
   1.653 +                                            gSurfaceMemoryUsed[i],
   1.654 +                                            nsCString(desc), aClosure);
   1.655 +                NS_ENSURE_SUCCESS(rv, rv);
   1.656 +            }
   1.657 +        }
   1.658 +
   1.659 +        return NS_OK;
   1.660 +    }
   1.661 +};
   1.662 +
   1.663 +NS_IMPL_ISUPPORTS(SurfaceMemoryReporter, nsIMemoryReporter)
   1.664 +
   1.665 +void
   1.666 +gfxASurface::RecordMemoryUsedForSurfaceType(gfxSurfaceType aType,
   1.667 +                                            int32_t aBytes)
   1.668 +{
   1.669 +    if (int(aType) < 0 || aType >= gfxSurfaceType::Max) {
   1.670 +        NS_WARNING("Invalid type to RecordMemoryUsedForSurfaceType!");
   1.671 +        return;
   1.672 +    }
   1.673 +
   1.674 +    static bool registered = false;
   1.675 +    if (!registered) {
   1.676 +        RegisterStrongMemoryReporter(new SurfaceMemoryReporter());
   1.677 +        registered = true;
   1.678 +    }
   1.679 +
   1.680 +    gSurfaceMemoryUsed[size_t(aType)] += aBytes;
   1.681 +}
   1.682 +
   1.683 +void
   1.684 +gfxASurface::RecordMemoryUsed(int32_t aBytes)
   1.685 +{
   1.686 +    RecordMemoryUsedForSurfaceType(GetType(), aBytes);
   1.687 +    mBytesRecorded += aBytes;
   1.688 +}
   1.689 +
   1.690 +void
   1.691 +gfxASurface::RecordMemoryFreed()
   1.692 +{
   1.693 +    if (mBytesRecorded) {
   1.694 +        RecordMemoryUsedForSurfaceType(GetType(), -mBytesRecorded);
   1.695 +        mBytesRecorded = 0;
   1.696 +    }
   1.697 +}
   1.698 +
   1.699 +size_t
   1.700 +gfxASurface::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
   1.701 +{
   1.702 +    // We don't measure mSurface because cairo doesn't allow it.
   1.703 +    return 0;
   1.704 +}
   1.705 +
   1.706 +size_t
   1.707 +gfxASurface::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
   1.708 +{
   1.709 +    return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
   1.710 +}
   1.711 +
   1.712 +/* static */ uint8_t
   1.713 +gfxASurface::BytesPerPixel(gfxImageFormat aImageFormat)
   1.714 +{
   1.715 +  switch (aImageFormat) {
   1.716 +    case gfxImageFormat::ARGB32:
   1.717 +      return 4;
   1.718 +    case gfxImageFormat::RGB24:
   1.719 +      return 4;
   1.720 +    case gfxImageFormat::RGB16_565:
   1.721 +      return 2;
   1.722 +    case gfxImageFormat::A8:
   1.723 +      return 1;
   1.724 +    case gfxImageFormat::A1:
   1.725 +      return 1; // Close enough
   1.726 +    case gfxImageFormat::Unknown:
   1.727 +    default:
   1.728 +      NS_NOTREACHED("Not really sure what you want me to say here");
   1.729 +      return 0;
   1.730 +  }
   1.731 +}
   1.732 +
   1.733 +void
   1.734 +gfxASurface::WriteAsPNG(const char* aFile)
   1.735 +{
   1.736 +    FILE *file = fopen(aFile, "wb");
   1.737 +    if (file) {
   1.738 +      WriteAsPNG_internal(file, true);
   1.739 +      fclose(file);
   1.740 +    } else {
   1.741 +      NS_WARNING("Failed to create file!\n");
   1.742 +    }
   1.743 +}
   1.744 +
   1.745 +void
   1.746 +gfxASurface::DumpAsDataURL(FILE* aOutput)
   1.747 +{
   1.748 +  WriteAsPNG_internal(aOutput, false);
   1.749 +}
   1.750 +
   1.751 +void
   1.752 +gfxASurface::PrintAsDataURL()
   1.753 +{
   1.754 +  WriteAsPNG_internal(stdout, false);
   1.755 +  fprintf(stdout, "\n");
   1.756 +}
   1.757 +
   1.758 +void
   1.759 +gfxASurface::CopyAsDataURL()
   1.760 +{
   1.761 +  WriteAsPNG_internal(nullptr, false);
   1.762 +}
   1.763 +
   1.764 +/**
   1.765 + * Write to a PNG file. If aBinary is true, then it is written
   1.766 + * as binary, otherwise as a data URL. If no file is specified then
   1.767 + * data is copied to the clipboard (must not be binary!).
   1.768 + */
   1.769 +void
   1.770 +gfxASurface::WriteAsPNG_internal(FILE* aFile, bool aBinary)
   1.771 +{
   1.772 +  nsRefPtr<gfxImageSurface> imgsurf = GetAsImageSurface();
   1.773 +  nsIntSize size;
   1.774 +
   1.775 +  // FIXME/bug 831898: hack r5g6b5 for now.
   1.776 +  if (!imgsurf || imgsurf->Format() == gfxImageFormat::RGB16_565) {
   1.777 +    size = GetSize();
   1.778 +    if (size.width == -1 && size.height == -1) {
   1.779 +      printf("Could not determine surface size\n");
   1.780 +      return;
   1.781 +    }
   1.782 +
   1.783 +    imgsurf =
   1.784 +      new gfxImageSurface(nsIntSize(size.width, size.height),
   1.785 +                          gfxImageFormat::ARGB32);
   1.786 +
   1.787 +    if (!imgsurf || imgsurf->CairoStatus()) {
   1.788 +      printf("Could not allocate image surface\n");
   1.789 +      return;
   1.790 +    }
   1.791 +
   1.792 +    nsRefPtr<gfxContext> ctx = new gfxContext(imgsurf);
   1.793 +    if (!ctx || ctx->HasError()) {
   1.794 +      printf("Could not allocate image context\n");
   1.795 +      return;
   1.796 +    }
   1.797 +
   1.798 +    ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
   1.799 +    ctx->SetSource(this, gfxPoint(0, 0));
   1.800 +    ctx->Paint();
   1.801 +  }
   1.802 +  size = imgsurf->GetSize();
   1.803 +
   1.804 +  nsCOMPtr<imgIEncoder> encoder =
   1.805 +    do_CreateInstance("@mozilla.org/image/encoder;2?type=image/png");
   1.806 +  if (!encoder) {
   1.807 +    int32_t w = std::min(size.width, 8);
   1.808 +    int32_t h = std::min(size.height, 8);
   1.809 +    printf("Could not create encoder. Printing %dx%d pixels.\n", w, h);
   1.810 +    for (int32_t y = 0; y < h; ++y) {
   1.811 +      for (int32_t x = 0; x < w; ++x) {
   1.812 +        printf("%x ", reinterpret_cast<uint32_t*>(imgsurf->Data())[y*imgsurf->Stride()+ x]);
   1.813 +      }
   1.814 +    }
   1.815 +    return;
   1.816 +  }
   1.817 +
   1.818 +  nsresult rv = encoder->InitFromData(imgsurf->Data(),
   1.819 +                                      size.width * size.height * 4,
   1.820 +                                      size.width,
   1.821 +                                      size.height,
   1.822 +                                      imgsurf->Stride(),
   1.823 +                                      imgIEncoder::INPUT_FORMAT_HOSTARGB,
   1.824 +                                      NS_LITERAL_STRING(""));
   1.825 +  if (NS_FAILED(rv))
   1.826 +    return;
   1.827 +
   1.828 +  nsCOMPtr<nsIInputStream> imgStream;
   1.829 +  CallQueryInterface(encoder.get(), getter_AddRefs(imgStream));
   1.830 +  if (!imgStream)
   1.831 +    return;
   1.832 +
   1.833 +  uint64_t bufSize64;
   1.834 +  rv = imgStream->Available(&bufSize64);
   1.835 +  if (NS_FAILED(rv))
   1.836 +    return;
   1.837 +
   1.838 +  if (bufSize64 > UINT32_MAX - 16)
   1.839 +    return;
   1.840 +
   1.841 +  uint32_t bufSize = (uint32_t)bufSize64;
   1.842 +
   1.843 +  // ...leave a little extra room so we can call read again and make sure we
   1.844 +  // got everything. 16 bytes for better padding (maybe)
   1.845 +  bufSize += 16;
   1.846 +  uint32_t imgSize = 0;
   1.847 +  char* imgData = (char*)moz_malloc(bufSize);
   1.848 +  if (!imgData)
   1.849 +    return;
   1.850 +  uint32_t numReadThisTime = 0;
   1.851 +  while ((rv = imgStream->Read(&imgData[imgSize],
   1.852 +                               bufSize - imgSize,
   1.853 +                               &numReadThisTime)) == NS_OK && numReadThisTime > 0)
   1.854 +  {
   1.855 +    imgSize += numReadThisTime;
   1.856 +    if (imgSize == bufSize) {
   1.857 +      // need a bigger buffer, just double
   1.858 +      bufSize *= 2;
   1.859 +      char* newImgData = (char*)moz_realloc(imgData, bufSize);
   1.860 +      if (!newImgData) {
   1.861 +        moz_free(imgData);
   1.862 +        return;
   1.863 +      }
   1.864 +      imgData = newImgData;
   1.865 +    }
   1.866 +  }
   1.867 +
   1.868 +  if (aBinary) {
   1.869 +    if (aFile) {
   1.870 +      fwrite(imgData, 1, imgSize, aFile);
   1.871 +    } else {
   1.872 +      NS_WARNING("Can't write binary image data without a file!");
   1.873 +    }
   1.874 +    return;
   1.875 +  }
   1.876 +
   1.877 +  // base 64, result will be null-terminated
   1.878 +  nsCString encodedImg;
   1.879 +  rv = Base64Encode(Substring(imgData, imgSize), encodedImg);
   1.880 +  moz_free(imgData);
   1.881 +  if (NS_FAILED(rv)) // not sure why this would fail
   1.882 +    return;
   1.883 +
   1.884 +  nsCString string("data:image/png;base64,");
   1.885 +  string.Append(encodedImg);
   1.886 +
   1.887 +  if (aFile) {
   1.888 +#ifdef ANDROID
   1.889 +     if (aFile == stdout || aFile == stderr) {
   1.890 +       // ADB logcat cuts off long strings so we will break it down
   1.891 +       const char* cStr = string.BeginReading();
   1.892 +       size_t len = strlen(cStr);
   1.893 +       while (true) {
   1.894 +         printf_stderr("IMG: %.140s\n", cStr);
   1.895 +         if (len <= 140)
   1.896 +           break;
   1.897 +         len -= 140;
   1.898 +         cStr += 140;
   1.899 +       }
   1.900 +     }
   1.901 +#endif
   1.902 +    fprintf(aFile, "%s", string.BeginReading());
   1.903 +  } else {
   1.904 +    nsCOMPtr<nsIClipboardHelper> clipboard(do_GetService("@mozilla.org/widget/clipboardhelper;1", &rv));
   1.905 +    if (clipboard) {
   1.906 +      clipboard->CopyString(NS_ConvertASCIItoUTF16(string), nullptr);
   1.907 +    }
   1.908 +  }
   1.909 +
   1.910 +  return;
   1.911 +}
   1.912 +
   1.913 +void
   1.914 +gfxASurface::SetOpaqueRect(const gfxRect& aRect)
   1.915 +{
   1.916 +    if (aRect.IsEmpty()) {
   1.917 +        mOpaqueRect = nullptr;
   1.918 +    } else if (!!mOpaqueRect) {
   1.919 +        *mOpaqueRect = aRect;
   1.920 +    } else {
   1.921 +        mOpaqueRect = new gfxRect(aRect);
   1.922 +    }
   1.923 +}
   1.924 +
   1.925 +/* static */const gfxRect&
   1.926 +gfxASurface::GetEmptyOpaqueRect()
   1.927 +{
   1.928 +  static const gfxRect empty(0, 0, 0, 0);
   1.929 +  return empty;
   1.930 +}
   1.931 +
   1.932 +const nsIntSize
   1.933 +gfxASurface::GetSize() const
   1.934 +{
   1.935 +  return nsIntSize(-1, -1);
   1.936 +}
   1.937 +
   1.938 +already_AddRefed<gfxImageSurface>
   1.939 +gfxASurface::GetAsImageSurface()
   1.940 +{
   1.941 +  return nullptr;
   1.942 +}

mercurial