diff options
author | Derek Sollenberger <djsollen@google.com> | 2012-01-18 08:56:56 -0500 |
---|---|---|
committer | Derek Sollenberger <derek@android.com> | 2012-02-06 14:14:40 -0500 |
commit | 1cab2921ab279367f8206cdadc9259d12e603548 (patch) | |
tree | 2852f9dc2481f639122e18fc7831ae6ca43d6d5a /include | |
parent | d7176fd5571bc9878d3cdac8696eaa35ec170d9d (diff) | |
download | external_skia-1cab2921ab279367f8206cdadc9259d12e603548.zip external_skia-1cab2921ab279367f8206cdadc9259d12e603548.tar.gz external_skia-1cab2921ab279367f8206cdadc9259d12e603548.tar.bz2 |
Skia merge (revision 3022)
This CL has companion changes to account for API updates in...
(1) frameworks/base
(2) external/webkit
Change-Id: Ibb989e76e8bd24313849f9631dbef42cdef9eb7d
Diffstat (limited to 'include')
259 files changed, 12199 insertions, 4119 deletions
diff --git a/include/animator/SkAnimator.h b/include/animator/SkAnimator.h index 04d342c..e6c5583 100644 --- a/include/animator/SkAnimator.h +++ b/include/animator/SkAnimator.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkAnimator_DEFINED #define SkAnimator_DEFINED diff --git a/include/animator/SkAnimatorView.h b/include/animator/SkAnimatorView.h index 3c6c8a1..940dd26 100644 --- a/include/animator/SkAnimatorView.h +++ b/include/animator/SkAnimatorView.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkAnimatorView_DEFINED #define SkAnimatorView_DEFINED diff --git a/include/config/SkUserConfig.h b/include/config/SkUserConfig.h deleted file mode 100644 index c56d8cf..0000000 --- a/include/config/SkUserConfig.h +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SkUserConfig_DEFINED -#define SkUserConfig_DEFINED - -/* SkTypes.h, the root of the public header files, does the following trick: - - #include "SkPreConfig.h" - #include "SkUserConfig.h" - #include "SkPostConfig.h" - - SkPreConfig.h runs first, and it is responsible for initializing certain - skia defines. - - SkPostConfig.h runs last, and its job is to just check that the final - defines are consistent (i.e. that we don't have mutually conflicting - defines). - - SkUserConfig.h (this file) runs in the middle. It gets to change or augment - the list of flags initially set in preconfig, and then postconfig checks - that everything still makes sense. - - Below are optional defines that add, subtract, or change default behavior - in Skia. Your port can locally edit this file to enable/disable flags as - you choose, or these can be delared on your command line (i.e. -Dfoo). - - By default, this include file will always default to having all of the flags - commented out, so including it will have no effect. -*/ - -/////////////////////////////////////////////////////////////////////////////// - -/* Scalars (the fractional value type in skia) can be implemented either as - floats or 16.16 integers (fixed). Exactly one of these two symbols must be - defined. -*/ -//#define SK_SCALAR_IS_FLOAT -//#define SK_SCALAR_IS_FIXED - - -/* Somewhat independent of how SkScalar is implemented, Skia also wants to know - if it can use floats at all. Naturally, if SK_SCALAR_IS_FLOAT is defined, - SK_CAN_USE_FLOAT must be too; but if scalars are fixed, SK_CAN_USE_FLOAT - can go either way. - */ -//#define SK_CAN_USE_FLOAT - -/* For some performance-critical scalar operations, skia will optionally work - around the standard float operators if it knows that the CPU does not have - native support for floats. If your environment uses software floating point, - define this flag. - */ -//#define SK_SOFTWARE_FLOAT - - -/* Skia has lots of debug-only code. Often this is just null checks or other - parameter checking, but sometimes it can be quite intrusive (e.g. check that - each 32bit pixel is in premultiplied form). This code can be very useful - during development, but will slow things down in a shipping product. - - By default, these mutually exclusive flags are defined in SkPreConfig.h, - based on the presence or absence of NDEBUG, but that decision can be changed - here. - */ -//#define SK_DEBUG -//#define SK_RELEASE - - -/* If, in debugging mode, Skia needs to stop (presumably to invoke a debugger) - it will call SK_CRASH(). If this is not defined it, it is defined in - SkPostConfig.h to write to an illegal address - */ -//#define SK_CRASH() *(int *)(uintptr_t)0 = 0 - - -/* preconfig will have attempted to determine the endianness of the system, - but you can change these mutually exclusive flags here. - */ -//#define SK_CPU_BENDIAN -//#define SK_CPU_LENDIAN - - -/* Some compilers don't support long long for 64bit integers. If yours does - not, define this to the appropriate type. - */ -//#define SkLONGLONG int64_t - - -/* Some envorinments do not suport writable globals (eek!). If yours does not, - define this flag. - */ -//#define SK_USE_RUNTIME_GLOBALS - - -/* To write debug messages to a console, skia will call SkDebugf(...) following - printf conventions (e.g. const char* format, ...). If you want to redirect - this to something other than printf, define yours here - */ -//#define SkDebugf(...) MyFunction(__VA_ARGS__) - -/* To enable additional blitters (and fontscaler code) to support separate - alpha channels for R G B channels, define SK_SUPPORT_LCDTEXT - */ -//#define SK_SUPPORT_LCDTEXT - -/* If zlib is available and you want to support the flate compression - algorithm (used in PDF generation), define SK_ZLIB_INCLUDE to be the - include path. - */ -//#define SK_ZLIB_INCLUDE <zlib.h> - -/* Define this to allow PDF scalars above 32k. The PDF/A spec doesn't allow - them, but modern PDF interpreters should handle them just fine. - */ -//#define SK_ALLOW_LARGE_PDF_SCALARS - -/* Define this to remove dimension checks on bitmaps. Not all blits will be - correct yet, so this is mostly for debugging the implementation. - */ -//#define SK_ALLOW_OVER_32K_BITMAPS - -/* If SK_DEBUG is defined, then you can optionally define SK_SUPPORT_UNITTEST - which will run additional self-tests at startup. These can take a long time, - so this flag is optional. - */ -#ifdef SK_DEBUG -//#define SK_SUPPORT_UNITTEST -#endif - -/* Change the ordering to work in X windows. - */ -#ifdef SK_SAMPLES_FOR_X - #define SK_R32_SHIFT 16 - #define SK_G32_SHIFT 8 - #define SK_B32_SHIFT 0 - #define SK_A32_SHIFT 24 -#endif - -#endif diff --git a/include/config/sk_stdint.h b/include/config/sk_stdint.h index 9a5f5ca..360755e 100644 --- a/include/config/sk_stdint.h +++ b/include/config/sk_stdint.h @@ -1,13 +1,23 @@ -#ifndef sk_stdint_DEFINED
-#define sk_stdint_DEFINED
-
-typedef signed char int8_t;
-typedef unsigned char uint8_t;
-typedef short int16_t;
-typedef unsigned short uint16_t;
-typedef int int32_t;
-typedef unsigned uint32_t;
-typedef long long int64_t;
-typedef unsigned long long uint64_t;
-
-#endif
+ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef sk_stdint_DEFINED +#define sk_stdint_DEFINED + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef int int32_t; +typedef unsigned uint32_t; +typedef long long int64_t; +typedef unsigned long long uint64_t; + +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + +#endif diff --git a/include/core/Sk64.h b/include/core/Sk64.h index b40b27f..b86e0be 100644 --- a/include/core/Sk64.h +++ b/include/core/Sk64.h @@ -1,24 +1,16 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef Sk64_DEFINED #define Sk64_DEFINED #include "SkFixed.h" -#include "SkMath.h" /** \class Sk64 diff --git a/include/core/SkAdvancedTypefaceMetrics.h b/include/core/SkAdvancedTypefaceMetrics.h index 1b81909..09fc9a9 100644..100755 --- a/include/core/SkAdvancedTypefaceMetrics.h +++ b/include/core/SkAdvancedTypefaceMetrics.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2011 Google Inc. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkAdvancedTypefaceMetrics_DEFINED #define SkAdvancedTypefaceMetrics_DEFINED @@ -139,10 +132,21 @@ void finishRange( typename SkAdvancedTypefaceMetrics::AdvanceMetric<Data>::MetricType type); +/** Retrieve advance data for glyphs. Used by the PDF backend. It calls + underlying platform dependent API getAdvance to acquire the data. + @param num_glyphs Total number of glyphs in the given font. + @param glyphIDs For per-glyph info, specify subset of the font by + giving glyph ids. Each integer represents a glyph + id. Passing NULL means all glyphs in the font. + @param glyphIDsCount Number of elements in subsetGlyphIds. Ignored if + glyphIDs is NULL. +*/ template <typename Data, typename FontHandle> SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* getAdvanceData( FontHandle fontHandle, int num_glyphs, + const uint32_t* glyphIDs, + uint32_t glyphIDsCount, bool (*getAdvance)(FontHandle fontHandle, int gId, Data* data)); } // namespace skia_advanced_typeface_metrics_utils diff --git a/include/core/SkAutoKern.h b/include/core/SkAutoKern.h index 023cb6b..7a5cdef 100644 --- a/include/core/SkAutoKern.h +++ b/include/core/SkAutoKern.h @@ -1,19 +1,11 @@ -/* libs/graphics/sgl/SkAutoKern.h -** -** Copyright 2006, The Android Open Source Project -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ + +/* + * Copyright 2006 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkAutoKern_DEFINED #define SkAutoKern_DEFINED diff --git a/include/core/SkBitmap.h b/include/core/SkBitmap.h index 91143c1..57b80e5 100644 --- a/include/core/SkBitmap.h +++ b/include/core/SkBitmap.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBitmap_DEFINED #define SkBitmap_DEFINED @@ -165,14 +158,41 @@ public: */ Sk64 getSafeSize64() const ; + /** Returns true if this bitmap is marked as immutable, meaning that the + contents of its pixels will not change for the lifetime of the bitmap. + */ + bool isImmutable() const; + + /** Marks this bitmap as immutable, meaning that the contents of its + pixels will not change for the lifetime of the bitmap and of the + underlying pixelref. This state can be set, but it cannot be + cleared once it is set. This state propagates to all other bitmaps + that share the same pixelref. + */ + void setImmutable(); + /** Returns true if the bitmap is opaque (has no translucent/transparent pixels). */ bool isOpaque() const; + /** Specify if this bitmap's pixels are all opaque or not. Is only meaningful for configs that support per-pixel alpha (RGB32, A1, A8). */ void setIsOpaque(bool); + /** Returns true if the bitmap is volatile (i.e. should not be cached by devices.) + */ + bool isVolatile() const; + + /** Specify whether this bitmap is volatile. Bitmaps are not volatile by + default. Temporary bitmaps that are discarded after use should be + marked as volatile. This provides a hint to the device that the bitmap + should not be cached. Providing this hint when appropriate can + improve performance by avoiding unnecessary overhead and resource + consumption on the device. + */ + void setIsVolatile(bool); + /** Reset the bitmap to its initial state (see default constructor). If we are a (shared) owner of the pixels, that ownership is decremented. */ @@ -218,12 +238,11 @@ public: /** Copies the bitmap's pixels to the location pointed at by dst and returns true if possible, returns false otherwise. - In the event that the bitmap's stride is equal to dstRowBytes, and if - it is greater than strictly required by the bitmap's current config - (this may happen if the bitmap is an extracted subset of another), then - this function will copy bytes past the eand of each row, excluding the - last row. No copies are made outside of the declared size of dst, - however. + In the case when the dstRowBytes matches the bitmap's rowBytes, the copy + may be made faster by copying over the dst's per-row padding (for all + rows but the last). By setting preserveDstPad to true the caller can + disable this optimization and ensure that pixels in the padding are not + overwritten. Always returns false for RLE formats. @@ -232,27 +251,12 @@ public: pixels using indicated stride. @param dstRowBytes Width of each line in the buffer. If -1, uses bitmap's internal stride. + @param preserveDstPad Must we preserve padding in the dst */ - bool copyPixelsTo(void* const dst, size_t dstSize, int dstRowBytes = -1) + bool copyPixelsTo(void* const dst, size_t dstSize, int dstRowBytes = -1, + bool preserveDstPad = false) const; - /** Copies the pixels at location src to the bitmap's pixel buffer. - Returns true if copy if possible (bitmap buffer is large enough), - false otherwise. - - Like copyPixelsTo, this function may write values beyond the end of - each row, although never outside the defined buffer. - - Always returns false for RLE formats. - - @param src Location of the source buffer. - @param srcSize Height of source buffer in pixels. - @param srcRowBytes Width of each line in the buffer. If -1, uses i - bitmap's internal stride. - */ - bool copyPixelsFrom(const void* const src, size_t srcSize, - int srcRowBytes = -1); - /** Use the standard HeapAllocator to create the pixelref that manages the pixel memory. It will be sized based on the current width/height/config. If this is called multiple times, a new pixelref object will be created @@ -316,6 +320,14 @@ public: */ void unlockPixels() const; + /** + * Some bitmaps can return a copy of their pixels for lockPixels(), but + * that copy, if modified, will not be pushed back. These bitmaps should + * not be used as targets for a raster device/canvas (since all pixels + * modifications will be lost when unlockPixels() is called.) + */ + bool lockPixelsAreWritable() const; + /** Call this to be sure that the bitmap is valid enough to be drawn (i.e. it has non-null pixels, and if required by its config, it has a non-null colortable. Returns true if all of the above are met. @@ -463,19 +475,29 @@ public: */ bool extractSubset(SkBitmap* dst, const SkIRect& subset) const; - /** Makes a deep copy of this bitmap, respecting the requested config. - Returns false if either there is an error (i.e. the src does not have - pixels) or the request cannot be satisfied (e.g. the src has per-pixel - alpha, and the requested config does not support alpha). - @param dst The bitmap to be sized and allocated - @param c The desired config for dst - @param allocator Allocator used to allocate the pixelref for the dst - bitmap. If this is null, the standard HeapAllocator - will be used. - @return true if the copy could be made. - */ + /** Makes a deep copy of this bitmap, respecting the requested config, + * and allocating the dst pixels on the cpu. + * Returns false if either there is an error (i.e. the src does not have + * pixels) or the request cannot be satisfied (e.g. the src has per-pixel + * alpha, and the requested config does not support alpha). + * @param dst The bitmap to be sized and allocated + * @param c The desired config for dst + * @param allocator Allocator used to allocate the pixelref for the dst + * bitmap. If this is null, the standard HeapAllocator + * will be used. + * @return true if the copy could be made. + */ bool copyTo(SkBitmap* dst, Config c, Allocator* allocator = NULL) const; + /** Makes a deep copy of this bitmap, respecting the requested config, and + * with custom allocation logic that will keep the copied pixels + * in the same domain as the source: If the src pixels are allocated for + * the cpu, then so will the dst. If the src pixels are allocated on the + * gpu (typically as a texture), the it will do the same for the dst. + * If the request cannot be fulfilled, returns false and dst is unmodified. + */ + bool deepCopyTo(SkBitmap* dst, Config c) const; + /** Returns true if this bitmap can be deep copied into the requested config by calling copyTo(). */ @@ -580,7 +602,9 @@ private: mutable int fRawPixelGenerationID; enum Flags { - kImageIsOpaque_Flag = 0x01 + kImageIsOpaque_Flag = 0x01, + kImageIsVolatile_Flag = 0x02, + kImageIsImmutable_Flag = 0x04 }; uint32_t fRowBytes; @@ -698,17 +722,23 @@ private: void inval16BitCache(); }; -class SkAutoLockPixels { +class SkAutoLockPixels : public SkNoncopyable { public: - SkAutoLockPixels(const SkBitmap& bitmap) : fBitmap(bitmap) { - bitmap.lockPixels(); + SkAutoLockPixels(const SkBitmap& bm, bool doLock = true) : fBitmap(bm) { + fDidLock = doLock; + if (doLock) { + bm.lockPixels(); + } } ~SkAutoLockPixels() { - fBitmap.unlockPixels(); + if (fDidLock) { + fBitmap.unlockPixels(); + } } private: const SkBitmap& fBitmap; + bool fDidLock; }; /** Helper class that performs the lock/unlockColors calls on a colortable. diff --git a/include/core/SkBlitRow.h b/include/core/SkBlitRow.h index bb8cbc2..fb62f5a 100644 --- a/include/core/SkBlitRow.h +++ b/include/core/SkBlitRow.h @@ -1,3 +1,10 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkBlitRow_DEFINED #define SkBlitRow_DEFINED @@ -25,8 +32,8 @@ public: @param x The x coordinate of the beginning of the scanline @param y THe y coordinate of the scanline */ - typedef void (*Proc)(uint16_t* SK_RESTRICT dst, - const SkPMColor* SK_RESTRICT src, + typedef void (*Proc)(uint16_t* dst, + const SkPMColor* src, int count, U8CPU alpha, int x, int y); /** Function pointer that blends a single color with a row of 32-bit colors @@ -51,8 +58,8 @@ public: @param count number of colors to blend @param alpha global alpha to be applied to all src colors */ - typedef void (*Proc32)(uint32_t* SK_RESTRICT dst, - const SkPMColor* SK_RESTRICT src, + typedef void (*Proc32)(uint32_t* dst, + const SkPMColor* src, int count, U8CPU alpha); static Proc32 Factory32(unsigned flags32); @@ -84,29 +91,4 @@ private: }; }; -/** - * Factory for blitmask procs - */ -class SkBlitMask { -public: - /** - * Function pointer that blits the mask into a device (dst) colorized - * by color. The number of pixels to blit is specified by width and height, - * but each scanline is offset by dstRB (rowbytes) and srcRB respectively. - */ - typedef void (*Proc)(void* dst, size_t dstRB, SkBitmap::Config dstConfig, - const uint8_t* mask, size_t maskRB, SkColor color, - int width, int height); - - /* Public entry-point to return a blitmask function ptr - */ - static Proc Factory(SkBitmap::Config dstConfig, SkColor color); - - /* return either platform specific optimized blitmask function-ptr, - * or NULL if no optimized - */ - static Proc PlatformProcs(SkBitmap::Config dstConfig, SkColor color); -}; - - #endif diff --git a/include/core/SkBlitter.h b/include/core/SkBlitter.h index 11b84fd..ce74a28 100644 --- a/include/core/SkBlitter.h +++ b/include/core/SkBlitter.h @@ -1,19 +1,11 @@ -/* libs/graphics/sgl/SkBlitter.h -** -** Copyright 2006, The Android Open Source Project -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ + +/* + * Copyright 2006 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkBlitter_DEFINED #define SkBlitter_DEFINED @@ -25,28 +17,49 @@ #include "SkRegion.h" #include "SkMask.h" +/** SkBlitter and its subclasses are responsible for actually writing pixels + into memory. Besides efficiency, they handle clipping and antialiasing. +*/ class SkBlitter { public: virtual ~SkBlitter(); + /// Blit a horizontal run of one or more pixels. virtual void blitH(int x, int y, int width); - virtual void blitAntiH(int x, int y, const SkAlpha[], const int16_t runs[]); + /// Blit a horizontal run of antialiased pixels; runs[] is a *sparse* + /// zero-terminated run-length encoding of spans of constant alpha values. + virtual void blitAntiH(int x, int y, const SkAlpha antialias[], + const int16_t runs[]); + /// Blit a vertical run of pixels with a constant alpha value. virtual void blitV(int x, int y, int height, SkAlpha alpha); + /// Blit a solid rectangle one or more pixels wide. virtual void blitRect(int x, int y, int width, int height); + /** Blit a rectangle with one alpha-blended column on the left, + width (zero or more) opaque pixels, and one alpha-blended column + on the right. + The result will always be at least two pixels wide. + */ + virtual void blitAntiRect(int x, int y, int width, int height, + SkAlpha leftAlpha, SkAlpha rightAlpha); + /// Blit a pattern of pixels defined by a rectangle-clipped mask; + /// typically used for text. virtual void blitMask(const SkMask&, const SkIRect& clip); - /* If the blitter just sets a single value for each pixel, return the + /** If the blitter just sets a single value for each pixel, return the bitmap it draws into, and assign value. If not, return NULL and ignore the value parameter. */ virtual const SkBitmap* justAnOpaqueColor(uint32_t* value); - // not virtual, just helpers + ///@name non-virtual helpers void blitMaskRegion(const SkMask& mask, const SkRegion& clip); void blitRectRegion(const SkIRect& rect, const SkRegion& clip); void blitRegion(const SkRegion& clip); + ///@} - // factories + /** @name Factories + Return the correct blitter to use given the specified context. + */ static SkBlitter* Choose(const SkBitmap& device, const SkMatrix& matrix, const SkPaint& paint) { @@ -63,6 +76,7 @@ public: const SkBitmap& src, int left, int top, void* storage, size_t storageSize); + ///@} private: }; @@ -71,12 +85,13 @@ private: */ class SkNullBlitter : public SkBlitter { public: - virtual void blitH(int x, int y, int width); - virtual void blitAntiH(int x, int y, const SkAlpha[], const int16_t runs[]); - virtual void blitV(int x, int y, int height, SkAlpha alpha); - virtual void blitRect(int x, int y, int width, int height); - virtual void blitMask(const SkMask&, const SkIRect& clip); - virtual const SkBitmap* justAnOpaqueColor(uint32_t* value); + virtual void blitH(int x, int y, int width) SK_OVERRIDE; + virtual void blitAntiH(int x, int y, const SkAlpha[], + const int16_t runs[]) SK_OVERRIDE; + virtual void blitV(int x, int y, int height, SkAlpha alpha) SK_OVERRIDE; + virtual void blitRect(int x, int y, int width, int height) SK_OVERRIDE; + virtual void blitMask(const SkMask&, const SkIRect& clip) SK_OVERRIDE; + virtual const SkBitmap* justAnOpaqueColor(uint32_t* value) SK_OVERRIDE; }; /** Wraps another (real) blitter, and ensures that the real blitter is only @@ -91,13 +106,15 @@ public: fClipRect = clipRect; } - // overrides - virtual void blitH(int x, int y, int width); - virtual void blitAntiH(int x, int y, const SkAlpha[], const int16_t runs[]); - virtual void blitV(int x, int y, int height, SkAlpha alpha); - virtual void blitRect(int x, int y, int width, int height); - virtual void blitMask(const SkMask&, const SkIRect& clip); - virtual const SkBitmap* justAnOpaqueColor(uint32_t* value); + virtual void blitH(int x, int y, int width) SK_OVERRIDE; + virtual void blitAntiH(int x, int y, const SkAlpha[], + const int16_t runs[]) SK_OVERRIDE; + virtual void blitV(int x, int y, int height, SkAlpha alpha) SK_OVERRIDE; + virtual void blitRect(int x, int y, int width, int height) SK_OVERRIDE; + virtual void blitAntiRect(int x, int y, int width, int height, + SkAlpha leftAlpha, SkAlpha rightAlpha) SK_OVERRIDE; + virtual void blitMask(const SkMask&, const SkIRect& clip) SK_OVERRIDE; + virtual const SkBitmap* justAnOpaqueColor(uint32_t* value) SK_OVERRIDE; private: SkBlitter* fBlitter; @@ -105,8 +122,8 @@ private: }; /** Wraps another (real) blitter, and ensures that the real blitter is only -called with coordinates that have been clipped by the specified clipRgn. -This means the caller need not perform the clipping ahead of time. + called with coordinates that have been clipped by the specified clipRgn. + This means the caller need not perform the clipping ahead of time. */ class SkRgnClipBlitter : public SkBlitter { public: @@ -116,19 +133,25 @@ public: fRgn = clipRgn; } - // overrides - virtual void blitH(int x, int y, int width); - virtual void blitAntiH(int x, int y, const SkAlpha[], const int16_t runs[]); - virtual void blitV(int x, int y, int height, SkAlpha alpha); - virtual void blitRect(int x, int y, int width, int height); - virtual void blitMask(const SkMask&, const SkIRect& clip); - virtual const SkBitmap* justAnOpaqueColor(uint32_t* value); + virtual void blitH(int x, int y, int width) SK_OVERRIDE; + virtual void blitAntiH(int x, int y, const SkAlpha[], + const int16_t runs[]) SK_OVERRIDE; + virtual void blitV(int x, int y, int height, SkAlpha alpha) SK_OVERRIDE; + virtual void blitRect(int x, int y, int width, int height) SK_OVERRIDE; + virtual void blitAntiRect(int x, int y, int width, int height, + SkAlpha leftAlpha, SkAlpha rightAlpha) SK_OVERRIDE; + virtual void blitMask(const SkMask&, const SkIRect& clip) SK_OVERRIDE; + virtual const SkBitmap* justAnOpaqueColor(uint32_t* value) SK_OVERRIDE; private: SkBlitter* fBlitter; const SkRegion* fRgn; }; +/** Factory to set up the appropriate most-efficient wrapper blitter + to apply a clip. Returns a pointer to a member, so lifetime must + be managed carefully. +*/ class SkBlitterClipper { public: SkBlitter* apply(SkBlitter* blitter, const SkRegion* clip, diff --git a/include/core/SkBounder.h b/include/core/SkBounder.h index fa4f7fb..5bac358 100644 --- a/include/core/SkBounder.h +++ b/include/core/SkBounder.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBounder_DEFINED #define SkBounder_DEFINED diff --git a/include/core/SkBuffer.h b/include/core/SkBuffer.h index 6745650..7a63d3a 100644 --- a/include/core/SkBuffer.h +++ b/include/core/SkBuffer.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBuffer_DEFINED #define SkBuffer_DEFINED diff --git a/include/core/SkCanvas.h b/include/core/SkCanvas.h index 273153f..24e4141 100644 --- a/include/core/SkCanvas.h +++ b/include/core/SkCanvas.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkCanvas_DEFINED #define SkCanvas_DEFINED @@ -30,11 +23,9 @@ class SkBounder; class SkDevice; -class SkDeviceFactory; class SkDraw; class SkDrawFilter; class SkPicture; -class SkShape; /** \class SkCanvas @@ -53,15 +44,10 @@ class SkShape; */ class SK_API SkCanvas : public SkRefCnt { public: - /** Construct a canvas with the given device factory. - @param factory Specify the factory for generating additional devices. - The factory may be null, in which case - SkRasterDeviceFactory will be used. - */ - explicit SkCanvas(SkDeviceFactory* factory = NULL); + SkCanvas(); + + /** Construct a canvas with the specified device to draw into. - /** Construct a canvas with the specified device to draw into. The device - factory will be retrieved from the passed device. @param device Specifies a device for the canvas to draw into. */ explicit SkCanvas(SkDevice* device); @@ -75,6 +61,13 @@ public: /////////////////////////////////////////////////////////////////////////// + /** + * Return the width/height of the underlying device. The current drawable + * area may be small (due to clipping or saveLayer). For a canvas with + * no device, 0,0 will be returned. + */ + SkISize getDeviceSize() const; + /** Return the canvas' device object, which may be null. The device holds the bitmap of the pixels that the canvas draws into. The reference count of the returned device is not changed by this call. @@ -96,49 +89,123 @@ public: */ SkDevice* getTopDevice() const; - /** May be overridden by subclasses. This returns a compatible device - for this canvas, with the specified config/width/height. If the device - is raster, the pixels will be allocated automatically. - */ - virtual SkDevice* createDevice(SkBitmap::Config, int width, int height, - bool isOpaque, bool forLayer = false); - /** * Create a new raster device and make it current. This also returns * the new device. */ - SkDevice* setBitmapDevice(const SkBitmap& bitmap, bool forLayer = false); + SkDevice* setBitmapDevice(const SkBitmap& bitmap); /** - * Return the current device factory, or NULL. The reference count of - * the returned factory is not changed. + * Shortcut for getDevice()->createCompatibleDevice(...). + * If getDevice() == NULL, this method does nothing, and returns NULL. */ - SkDeviceFactory* getDeviceFactory() const { return fDeviceFactory; } + SkDevice* createCompatibleDevice(SkBitmap::Config config, + int width, int height, + bool isOpaque); + + /////////////////////////////////////////////////////////////////////////// /** - * Replace any existing factory with the specified factory, unrefing the - * previous (if any), and refing the new one (if any). For convenience, - * the factory parameter is also returned. + * This enum can be used with read/writePixels to perform a pixel ops to or + * from an 8888 config other than Skia's native config (SkPMColor). There + * are three byte orders supported: native, BGRA, and RGBA. Each has a + * premultiplied and unpremultiplied variant. + * + * Components of a 8888 pixel can be packed/unpacked from a 32bit word using + * either byte offsets or shift values. Byte offsets are endian-invariant + * while shifts are not. BGRA and RGBA configs are defined by byte + * orderings. The native config is defined by shift values (SK_A32_SHIFT, + * ..., SK_B32_SHIFT). */ - SkDeviceFactory* setDeviceFactory(SkDeviceFactory*); + enum Config8888 { + /** + * Skia's native order specified by: + * SK_A32_SHIFT, SK_R32_SHIFT, SK_G32_SHIFT, and SK_B32_SHIFT + * + * kNative_Premul_Config8888 is equivalent to SkPMColor + * kNative_Unpremul_Config8888 has the same component order as SkPMColor + * but is not premultiplied. + */ + kNative_Premul_Config8888, + kNative_Unpremul_Config8888, + /** + * low byte to high byte: B, G, R, A. + */ + kBGRA_Premul_Config8888, + kBGRA_Unpremul_Config8888, + /** + * low byte to high byte: R, G, B, A. + */ + kRGBA_Premul_Config8888, + kRGBA_Unpremul_Config8888, + }; - /////////////////////////////////////////////////////////////////////////// + /** + * On success (returns true), copy the canvas pixels into the bitmap. + * On failure, the bitmap parameter is left unchanged and false is + * returned. + * + * The canvas' pixels are converted to the bitmap's config. The only + * supported config is kARGB_8888_Config, though this is likely to be + * relaxed in the future. The meaning of config kARGB_8888_Config is + * modified by the enum param config8888. The default value interprets + * kARGB_8888_Config as SkPMColor + * + * If the bitmap has pixels already allocated, the canvas pixels will be + * written there. If not, bitmap->allocPixels() will be called + * automatically. If the bitmap is backed by a texture readPixels will + * fail. + * + * The actual pixels written is the intersection of the canvas' bounds, and + * the rectangle formed by the bitmap's width,height and the specified x,y. + * If bitmap pixels extend outside of that intersection, they will not be + * modified. + * + * Other failure conditions: + * * If the canvas is backed by a non-raster device (e.g. PDF) then + * readPixels will fail. + * * If bitmap is texture-backed then readPixels will fail. (This may be + * relaxed in the future.) + * + * Example that reads the entire canvas into a bitmap using the native + * SkPMColor: + * SkISize size = canvas->getDeviceSize(); + * bitmap->setConfig(SkBitmap::kARGB_8888_Config, size.fWidth, + * size.fHeight); + * if (canvas->readPixels(bitmap, 0, 0)) { + * // use the pixels + * } + */ + bool readPixels(SkBitmap* bitmap, + int x, int y, + Config8888 config8888 = kNative_Premul_Config8888); /** - * Copy the pixels from the device into bitmap. Returns true on success. - * If false is returned, then the bitmap parameter is left unchanged. - * The bitmap parameter is treated as output-only, and will be completely - * overwritten (if the method returns true). + * DEPRECATED: This will be removed as soon as webkit is no longer relying + * on it. The bitmap is resized to the intersection of srcRect and the + * canvas bounds. New pixels are always allocated on success. Bitmap is + * unmodified on failure. */ bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap); - bool readPixels(SkBitmap* bitmap); /** * Similar to draw sprite, this method will copy the pixels in bitmap onto - * the device, with the top/left corner specified by (x, y). The pixel - * values in the device are completely replaced: there is no blending. + * the canvas, with the top/left corner specified by (x, y). The canvas' + * pixel values are completely replaced: there is no blending. + * + * Currently if bitmap is backed by a texture this is a no-op. This may be + * relaxed in the future. + * + * If the bitmap has config kARGB_8888_Config then the config8888 param + * will determines how the pixel valuess are intepreted. If the bitmap is + * not kARGB_8888_Config then this parameter is ignored. + * + * Note: If you are recording drawing commands on this canvas to + * SkPicture, writePixels() is ignored! */ - void writePixels(const SkBitmap& bitmap, int x, int y); + void writePixels(const SkBitmap& bitmap, + int x, int y, + Config8888 config8888 = kNative_Premul_Config8888); /////////////////////////////////////////////////////////////////////////// @@ -220,6 +287,11 @@ public: */ void restoreToCount(int saveCount); + /** Returns true if drawing is currently going to a layer (from saveLayer) + * rather than to the root device. + */ + bool isDrawingToLayer() const; + /** Preconcat the current matrix with the specified translation @param dx The distance to translate in X @param dy The distance to translate in Y @@ -268,7 +340,8 @@ public: @return true if the canvas' clip is non-empty */ virtual bool clipRect(const SkRect& rect, - SkRegion::Op op = SkRegion::kIntersect_Op); + SkRegion::Op op = SkRegion::kIntersect_Op, + bool doAntiAlias = false); /** Modify the current clip with the specified path. @param path The path to apply to the current clip @@ -276,7 +349,8 @@ public: @return true if the canvas' new clip is non-empty */ virtual bool clipPath(const SkPath& path, - SkRegion::Op op = SkRegion::kIntersect_Op); + SkRegion::Op op = SkRegion::kIntersect_Op, + bool doAntiAlias = false); /** Modify the current clip with the specified region. Note that unlike clipRect() and clipPath() which transform their arguments by the current @@ -359,6 +433,13 @@ public: */ bool getClipBounds(SkRect* bounds, EdgeType et = kAA_EdgeType) const; + /** Return the bounds of the current clip, in device coordinates; returns + true if non-empty. Maybe faster than getting the clip explicitly and + then taking its bounds. + */ + bool getClipDeviceBounds(SkIRect* bounds) const; + + /** Fill the entire canvas' bitmap (restricted to the current clip) with the specified ARGB color, using the specified mode. @param a the alpha component (0..255) of the color to fill the canvas @@ -565,6 +646,23 @@ public: virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m, const SkPaint* paint = NULL); + /** + * Draw the bitmap stretched differentially to fit into dst. + * center is a rect within the bitmap, and logically divides the bitmap + * into 9 sections (3x3). For example, if the middle pixel of a [5x5] + * bitmap is the "center", then the center-rect should be [2, 2, 3, 3]. + * + * If the dst is >= the bitmap size, then... + * - The 4 corners are not stretch at all. + * - The sides are stretch in only one axis. + * - The center is stretch in both axes. + * Else, for each axis where dst < bitmap, + * - The corners shrink proportionally + * - The sides (along the shrink axis) and center are not drawn + */ + virtual void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, + const SkRect& dst, const SkPaint* paint = NULL); + /** Draw the specified bitmap, with its top/left corner at (x,y), NOT transformed by the current matrix. Note: if the paint contains a maskfilter that generates a mask which extends beyond the @@ -643,7 +741,7 @@ public: const SkPath& path, const SkMatrix* matrix, const SkPaint& paint); -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID /** Draw the text on path, with each character/glyph origin specified by the pos[] array. The origin is interpreted by the Align setting in the paint. @param text The text to be drawn @@ -669,10 +767,6 @@ public: */ virtual void drawPicture(SkPicture& picture); - /** Draws the specified shape - */ - virtual void drawShape(SkShape*); - enum VertexMode { kTriangles_VertexMode, kTriangleStrip_VertexMode, @@ -753,6 +847,17 @@ public: */ const SkMatrix& getTotalMatrix() const; + enum ClipType { + kEmpty_ClipType = 0, + kRect_ClipType, + kComplex_ClipType + }; + + /** Returns a description of the total clip; may be cheaper than + getting the clip and querying it directly. + */ + ClipType getClipType() const; + /** Return the current device clip (concatenation of all clip calls). This does not account for the translate in any of the devices. @return the current device clip (concatenation of all clip calls). @@ -760,6 +865,14 @@ public: const SkRegion& getTotalClip() const; /** + * Return true if the current clip is non-empty. + * + * If bounds is not NULL, set it to the bounds of the current clip + * in global coordinates. + */ + bool getTotalClipBounds(SkIRect* bounds) const; + + /** * Return the current clipstack. This mirrors the result in getTotalClip() * but is represented as a stack of geometric clips + region-ops. */ @@ -824,7 +937,7 @@ private: SkBounder* fBounder; SkDevice* fLastDeviceToGainFocus; - SkDeviceFactory* fDeviceFactory; + int fLayerCount; // number of successful saveLayer calls void prepareForDeviceDraw(SkDevice*, const SkMatrix&, const SkRegion&, const SkClipStack& clipStack); @@ -834,13 +947,31 @@ private: friend class SkDrawIter; // needs setupDrawForLayerDevice() + SkDevice* createLayerDevice(SkBitmap::Config, int width, int height, + bool isOpaque); + SkDevice* init(SkDevice*); + + // internal methods are not virtual, so they can safely be called by other + // canvas apis, without confusing subclasses (like SkPictureRecording) void internalDrawBitmap(const SkBitmap&, const SkIRect*, const SkMatrix& m, const SkPaint* paint); + void internalDrawBitmapRect(const SkBitmap& bitmap, const SkIRect* src, + const SkRect& dst, const SkPaint* paint); + void internalDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, + const SkRect& dst, const SkPaint* paint); + void internalDrawPaint(const SkPaint& paint); + + void drawDevice(SkDevice*, int x, int y, const SkPaint*); // shared by save() and saveLayer() int internalSave(SaveFlags flags); void internalRestore(); + static void DrawRect(const SkDraw& draw, const SkPaint& paint, + const SkRect& r, SkScalar textSize); + static void DrawTextDecorations(const SkDraw& draw, const SkPaint& paint, + const char text[], size_t byteLength, + SkScalar x, SkScalar y); /* These maintain a cache of the clip bounds in local coordinates, (converted to 2s-compliment if floats are slow). @@ -918,4 +1049,3 @@ private: }; #endif - diff --git a/include/core/SkChunkAlloc.h b/include/core/SkChunkAlloc.h index ba9e2c9..28d3c7e 100644 --- a/include/core/SkChunkAlloc.h +++ b/include/core/SkChunkAlloc.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkChunkAlloc_DEFINED #define SkChunkAlloc_DEFINED diff --git a/include/core/SkClampRange.h b/include/core/SkClampRange.h index 9acf1ad..68a27e9 100644 --- a/include/core/SkClampRange.h +++ b/include/core/SkClampRange.h @@ -1,19 +1,12 @@ -/* - Copyright 2011 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkClampRange_DEFINED #define SkClampRange_DEFINED diff --git a/include/core/SkClipStack.h b/include/core/SkClipStack.h index 6e8da76..fc96f03 100644 --- a/include/core/SkClipStack.h +++ b/include/core/SkClipStack.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkClipStack_DEFINED #define SkClipStack_DEFINED @@ -27,10 +34,10 @@ public: SkRegion::Op op = SkRegion::kIntersect_Op) { SkRect r; r.set(ir); - this->clipDevRect(r, op); + this->clipDevRect(r, op, false); } - void clipDevRect(const SkRect&, SkRegion::Op = SkRegion::kIntersect_Op); - void clipDevPath(const SkPath&, SkRegion::Op = SkRegion::kIntersect_Op); + void clipDevRect(const SkRect&, SkRegion::Op, bool doAA); + void clipDevPath(const SkPath&, SkRegion::Op, bool doAA); class B2FIter { public: @@ -42,11 +49,13 @@ public: B2FIter(const SkClipStack& stack); struct Clip { + Clip() : fRect(NULL), fPath(NULL), fOp(SkRegion::kIntersect_Op) {} friend bool operator==(const Clip& a, const Clip& b); friend bool operator!=(const Clip& a, const Clip& b); const SkRect* fRect; // if non-null, this is a rect clip const SkPath* fPath; // if non-null, this is a path clip SkRegion::Op fOp; + bool fDoAA; }; /** diff --git a/include/core/SkColor.h b/include/core/SkColor.h index 1f82aa7..e6d4352 100644 --- a/include/core/SkColor.h +++ b/include/core/SkColor.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkColor_DEFINED #define SkColor_DEFINED diff --git a/include/core/SkColorFilter.h b/include/core/SkColorFilter.h index 3e9aee8..97db5cc 100644 --- a/include/core/SkColorFilter.h +++ b/include/core/SkColorFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkColorFilter_DEFINED #define SkColorFilter_DEFINED @@ -30,6 +23,31 @@ public: */ virtual bool asColorMode(SkColor* color, SkXfermode::Mode* mode); + /** + * If the filter can be represented by a 5x4 matrix, this + * returns true, and sets the matrix appropriately. + * If not, this returns false and ignores the parameter. + */ + virtual bool asColorMatrix(SkScalar matrix[20]); + + /** + * If the filter can be represented by per-component table, return true, + * and if table is not null, copy the bitmap containing the table into it. + * + * The table bitmap will be in SkBitmap::kA8_Config. Each row corresponding + * to each component in ARGB order. e.g. row[0] == alpha, row[1] == red, + * etc. To transform a color, you (logically) perform the following: + * + * a' = *table.getAddr8(a, 0); + * r' = *table.getAddr8(r, 1); + * g' = *table.getAddr8(g, 2); + * b' = *table.getAddr8(b, 3); + * + * The original component value is the horizontal index for a given row, + * and the stored value at that index is the new value for that component. + */ + virtual bool asComponentTable(SkBitmap* table); + /** Called with a scanline of colors, as if there was a shader installed. The implementation writes out its filtered version into result[]. Note: shader and result may be the same buffer. @@ -99,7 +117,8 @@ public: are ignored. */ static SkColorFilter* CreateLightingFilter(SkColor mul, SkColor add); - + + SK_DECLARE_FLATTENABLE_REGISTRAR() protected: SkColorFilter() {} SkColorFilter(SkFlattenableReadBuffer& rb) : INHERITED(rb) {} @@ -126,8 +145,8 @@ public: protected: SkFilterShader(SkFlattenableReadBuffer& ); - virtual void flatten(SkFlattenableWriteBuffer& ); - virtual Factory getFactory() { return CreateProc; } + virtual void flatten(SkFlattenableWriteBuffer& ) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE { return CreateProc; } private: static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(SkFilterShader, (buffer)); } diff --git a/include/core/SkColorPriv.h b/include/core/SkColorPriv.h index 6fa9df3..714e845 100644 --- a/include/core/SkColorPriv.h +++ b/include/core/SkColorPriv.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkColorPriv_DEFINED #define SkColorPriv_DEFINED @@ -51,6 +44,21 @@ static inline int SkAlphaBlend(int src, int dst, int scale256) { return dst + SkAlphaMul(src - dst, scale256); } +/** + * Returns (src * alpha + dst * (255 - alpha)) / 255 + * + * This is more accurate than SkAlphaBlend, but slightly slower + */ +static inline int SkAlphaBlend255(S16CPU src, S16CPU dst, U8CPU alpha) { + SkASSERT((int16_t)src == src); + SkASSERT((int16_t)dst == dst); + SkASSERT((uint8_t)alpha == alpha); + + int prod = SkMulS16(src - dst, alpha) + 128; + prod = (prod + (prod >> 8)) >> 8; + return dst + prod; +} + #define SK_R16_BITS 5 #define SK_G16_BITS 6 #define SK_B16_BITS 5 @@ -216,6 +224,21 @@ static inline SkPMColor SkPackARGB32NoCheck(U8CPU a, U8CPU r, U8CPU g, U8CPU b) (g << SK_G32_SHIFT) | (b << SK_B32_SHIFT); } +static inline +SkPMColor SkPremultiplyARGBInline(U8CPU a, U8CPU r, U8CPU g, U8CPU b) { + SkA32Assert(a); + SkA32Assert(r); + SkA32Assert(g); + SkA32Assert(b); + + if (a != 255) { + r = SkMulDiv255Round(r, a); + g = SkMulDiv255Round(g, a); + b = SkMulDiv255Round(b, a); + } + return SkPackARGB32(a, r, g, b); +} + SK_API extern const uint32_t gMask_00FF00FF; static inline uint32_t SkAlphaMulQ(uint32_t c, unsigned scale) { diff --git a/include/core/SkColorShader.h b/include/core/SkColorShader.h index b7537e1..9b1fed3 100644 --- a/include/core/SkColorShader.h +++ b/include/core/SkColorShader.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2007 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkColorShader_DEFINED #define SkColorShader_DEFINED @@ -39,38 +32,38 @@ public: virtual ~SkColorShader(); - virtual uint32_t getFlags() { return fFlags; } - virtual uint8_t getSpan16Alpha() const; + virtual uint32_t getFlags() SK_OVERRIDE; + virtual uint8_t getSpan16Alpha() const SK_OVERRIDE; + virtual bool isOpaque() const SK_OVERRIDE; virtual bool setContext(const SkBitmap& device, const SkPaint& paint, - const SkMatrix& matrix); - virtual void shadeSpan(int x, int y, SkPMColor span[], int count); - virtual void shadeSpan16(int x, int y, uint16_t span[], int count); - virtual void shadeSpanAlpha(int x, int y, uint8_t alpha[], int count); + const SkMatrix& matrix) SK_OVERRIDE; + virtual void shadeSpan(int x, int y, SkPMColor span[], int count) SK_OVERRIDE; + virtual void shadeSpan16(int x, int y, uint16_t span[], int count) SK_OVERRIDE; + virtual void shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) SK_OVERRIDE; + // we return false for this, use asAGradient virtual BitmapType asABitmap(SkBitmap* outTexture, SkMatrix* outMatrix, TileMode xy[2], - SkScalar* twoPointRadialParams) const; + SkScalar* twoPointRadialParams) const SK_OVERRIDE; - virtual GradientType asAGradient(GradientInfo* info) const; + virtual GradientType asAGradient(GradientInfo* info) const SK_OVERRIDE; protected: - SkColorShader(SkFlattenableReadBuffer& ); - virtual void flatten(SkFlattenableWriteBuffer& ); - virtual Factory getFactory() { return CreateProc; } + SkColorShader(SkFlattenableReadBuffer&); + + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; + private: - static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { - return SkNEW_ARGS(SkColorShader, (buffer)); - } + static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + SkColor fColor; // ignored if fInheritColor is true SkPMColor fPMColor; // cached after setContext() uint32_t fFlags; // cached after setContext() uint16_t fColor16; // cached after setContext() SkBool8 fInheritColor; - // deferred allocation, used for asABitmap() - mutable SkPixelRef* fAsABitmapPixelRef; - typedef SkShader INHERITED; }; diff --git a/include/core/SkComposeShader.h b/include/core/SkComposeShader.h index ea37549..f243954 100644 --- a/include/core/SkComposeShader.h +++ b/include/core/SkComposeShader.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkComposeShader_DEFINED #define SkComposeShader_DEFINED diff --git a/include/core/SkData.h b/include/core/SkData.h new file mode 100644 index 0000000..a134536 --- /dev/null +++ b/include/core/SkData.h @@ -0,0 +1,137 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef SkData_DEFINED +#define SkData_DEFINED + +#include "SkRefCnt.h" + +/** + * SkData holds an immutable data buffer. Not only is the data immutable, + * but the actual ptr that is returned (by data() or bytes()) is guaranteed + * to always be the same for the life of this instance. + */ +class SkData : public SkRefCnt { +public: + /** + * Returns the number of bytes stored. + */ + size_t size() const { return fSize; } + + /** + * Returns the ptr to the data. + */ + const void* data() const { return fPtr; } + + /** + * Like data(), returns a read-only ptr into the data, but in this case + * it is cast to uint8_t*, to make it easy to add an offset to it. + */ + const uint8_t* bytes() const { + return reinterpret_cast<const uint8_t*>(fPtr); + } + + /** + * Helper to copy a range of the data into a caller-provided buffer. + * Returns the actual number of bytes copied, after clamping offset and + * length to the size of the data. If buffer is NULL, it is ignored, and + * only the computed number of bytes is returned. + */ + size_t copyRange(size_t offset, size_t length, void* buffer) const; + + /** + * Function that, if provided, will be called when the SkData goes out + * of scope, allowing for custom allocation/freeing of the data. + */ + typedef void (*ReleaseProc)(const void* ptr, size_t length, void* context); + + /** + * Create a new dataref by copying the specified data + */ + static SkData* NewWithCopy(const void* data, size_t length); + + /** + * Create a new dataref, taking the data ptr as is, and using the + * releaseproc to free it. The proc may be NULL. + */ + static SkData* NewWithProc(const void* data, size_t length, + ReleaseProc proc, void* context); + + /** + * Create a new dataref, reference the data ptr as is, and calling + * sk_free to delete it. + */ + static SkData* NewFromMalloc(const void* data, size_t length); + + /** + * Create a new dataref using a subset of the data in the specified + * src dataref. + */ + static SkData* NewSubset(const SkData* src, size_t offset, size_t length); + + /** + * Returns a new empty dataref (or a reference to a shared empty dataref). + * New or shared, the caller must see that unref() is eventually called. + */ + static SkData* NewEmpty(); + +private: + ReleaseProc fReleaseProc; + void* fReleaseProcContext; + + const void* fPtr; + size_t fSize; + + SkData(const void* ptr, size_t size, ReleaseProc, void* context); + ~SkData(); +}; + +/** + * Specialized version of SkAutoTUnref<SkData> for automatically unref-ing a + * SkData. If the SkData is null, data(), bytes() and size() will return 0. + */ +class SkAutoDataUnref : SkNoncopyable { +public: + SkAutoDataUnref(SkData* data) : fRef(data) { + if (data) { + fData = data->data(); + fSize = data->size(); + } else { + fData = NULL; + fSize = 0; + } + } + ~SkAutoDataUnref() { + SkSafeUnref(fRef); + } + + const void* data() const { return fData; } + const uint8_t* bytes() const { + return reinterpret_cast<const uint8_t*> (fData); + } + size_t size() const { return fSize; } + SkData* get() const { return fRef; } + + void release() { + if (fRef) { + fRef->unref(); + fRef = NULL; + fData = NULL; + fSize = 0; + } + } + +private: + SkData* fRef; + const void* fData; + size_t fSize; +}; + +#endif diff --git a/include/core/SkDeque.h b/include/core/SkDeque.h index 8bf8b5b..b4f420d 100644 --- a/include/core/SkDeque.h +++ b/include/core/SkDeque.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDeque_DEFINED #define SkDeque_DEFINED diff --git a/include/core/SkDescriptor.h b/include/core/SkDescriptor.h index 09397b7..b97b75f 100644 --- a/include/core/SkDescriptor.h +++ b/include/core/SkDescriptor.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDescriptor_DEFINED #define SkDescriptor_DEFINED diff --git a/include/core/SkDevice.h b/include/core/SkDevice.h index d9a4fde..c026a4b 100644 --- a/include/core/SkDevice.h +++ b/include/core/SkDevice.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2010 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDevice_DEFINED #define SkDevice_DEFINED @@ -23,55 +16,57 @@ #include "SkColor.h" class SkClipStack; -class SkDevice; class SkDraw; struct SkIRect; class SkMatrix; class SkMetaData; class SkRegion; -/** \class SkDeviceFactory - - Devices that extend SkDevice should also provide a SkDeviceFactory class - to pass into SkCanvas. Doing so will eliminate the need to extend - SkCanvas as well. -*/ -class SK_API SkDeviceFactory : public SkRefCnt { -public: - SkDeviceFactory(); - virtual ~SkDeviceFactory(); - virtual SkDevice* newDevice(SkCanvas*, SkBitmap::Config, int width, - int height, bool isOpaque, bool isLayer) = 0; -}; - -class SkRasterDeviceFactory : public SkDeviceFactory { -public: - virtual SkDevice* newDevice(SkCanvas*, SkBitmap::Config, int width, - int height, bool isOpaque, bool isLayer); -}; +// This is an opaque class, not interpreted by skia +class SkGpuRenderTarget; class SK_API SkDevice : public SkRefCnt { public: - SkDevice(SkCanvas*); - /** Construct a new device, extracting the width/height/config/isOpaque values from - the bitmap. If transferPixelOwnership is true, and the bitmap claims to own its - own pixels (getOwnsPixels() == true), then transfer this responsibility to the - device, and call setOwnsPixels(false) on the bitmap. + /** + * Construct a new device with the specified bitmap as its backend. It is + * valid for the bitmap to have no pixels associated with it. In that case, + * any drawing to this device will have no effect. + */ + SkDevice(const SkBitmap& bitmap); - Subclasses may override the destructor, which is virtual, even though this class - doesn't have one. SkRefCnt does. + /** + * Create a new raster device and have the pixels be automatically + * allocated. The rowBytes of the device will be computed automatically + * based on the config and the width. + * + * @param config The desired config for the pixels. If the request cannot + * be met, the closest matching support config will be used. + * @param width width (in pixels) of the device + * @param height height (in pixels) of the device + * @param isOpaque Set to true if it is known that all of the pixels will + * be drawn to opaquely. Used as an accelerator when drawing + * these pixels to another device. + */ + SkDevice(SkBitmap::Config config, int width, int height, bool isOpaque = false); - @param bitmap A copy of this bitmap is made and stored in the device - */ - SkDevice(SkCanvas*, const SkBitmap& bitmap, bool forOffscreen); virtual ~SkDevice(); /** - * Return the factory that will create this subclass of SkDevice. - * The returned factory is cached by the device, and so its reference count - * is not changed by this call. + * Creates a device that is of the same type as this device (e.g. SW-raster, + * GPU, or PDF). The backing store for this device is created automatically + * (e.g. offscreen pixels or FBO or whatever is appropriate). + * + * @param width width of the device to create + * @param height height of the device to create + * @param isOpaque performance hint, set to true if you know that you will + * draw into this device such that all of the pixels will + * be opaque. */ - SkDeviceFactory* getDeviceFactory(); + SkDevice* createCompatibleDevice(SkBitmap::Config config, + int width, int height, + bool isOpaque); + + SkMetaData& getMetaData(); enum Capabilities { kGL_Capability = 0x1, //!< mask indicating GL support @@ -88,28 +83,20 @@ public: virtual int height() const { return fBitmap.height(); } /** - * Return the device's origin: its offset in device coordinates from - * the default origin in its canvas' matrix/clip + * Return the bounds of the device in the coordinate space of the root + * canvas. The root device will have its top-left at 0,0, but other devices + * such as those associated with saveLayer may have a non-zero origin. */ - const SkIPoint& getOrigin() const { return fOrigin; } + void getGlobalBounds(SkIRect* bounds) const; - /** Return the bitmap config of the device's pixels - */ - SkBitmap::Config config() const { return fBitmap.getConfig(); } /** Returns true if the device's bitmap's config treats every pixels as implicitly opaque. */ bool isOpaque() const { return fBitmap.isOpaque(); } - /** Return the bounds of the device - */ - void getBounds(SkIRect* bounds) const; - - /** Return true if the specified rectangle intersects the bounds of the - device. If sect is not NULL and there is an intersection, sect returns - the intersection. + /** Return the bitmap config of the device's pixels */ - bool intersects(const SkIRect& r, SkIRect* sect = NULL) const; + SkBitmap::Config config() const { return fBitmap.getConfig(); } /** Return the bitmap associated with this device. Call this each time you need to access the bitmap, as it notifies the subclass to perform any flushing @@ -119,26 +106,56 @@ public: */ const SkBitmap& accessBitmap(bool changePixels); - /** Clears the entire device to the specified color (including alpha). - * Ignores the clip. + /** + * DEPRECATED: This will be made protected once WebKit stops using it. + * Instead use Canvas' writePixels method. + * + * Similar to draw sprite, this method will copy the pixels in bitmap onto + * the device, with the top/left corner specified by (x, y). The pixel + * values in the device are completely replaced: there is no blending. + * + * Currently if bitmap is backed by a texture this is a no-op. This may be + * relaxed in the future. + * + * If the bitmap has config kARGB_8888_Config then the config8888 param + * will determines how the pixel valuess are intepreted. If the bitmap is + * not kARGB_8888_Config then this parameter is ignored. */ - virtual void clear(SkColor color); + virtual void writePixels(const SkBitmap& bitmap, int x, int y, + SkCanvas::Config8888 config8888 = SkCanvas::kNative_Premul_Config8888); /** - * Deprecated name for clear. + * Return the device's associated gpu render target, or NULL. */ - void eraseColor(SkColor eraseColor) { this->clear(eraseColor); } + virtual SkGpuRenderTarget* accessRenderTarget() { return NULL; } - /** Called when this device is installed into a Canvas. Balanaced by a call - to unlockPixels() when the device is removed from a Canvas. - */ - virtual void lockPixels(); - virtual void unlockPixels(); - /** Return the device's associated texture, or NULL. If returned, it may be - drawn into another device + /** + * Return the device's origin: its offset in device coordinates from + * the default origin in its canvas' matrix/clip + */ + const SkIPoint& getOrigin() const { return fOrigin; } + +protected: + enum Usage { + kGeneral_Usage, + kSaveLayer_Usage, // <! internal use only + }; + + struct TextFlags { + uint32_t fFlags; // SkPaint::getFlags() + SkPaint::Hinting fHinting; + }; + + /** + * Device may filter the text flags for drawing text here. If it wants to + * make a change to the specified values, it should write them into the + * textflags parameter (output) and return true. If the paint is fine as + * is, then ignore the textflags parameter and return false. + * + * The baseclass SkDevice filters based on its depth and blitters. */ - virtual SkGpuTexture* accessTexture() { return NULL; } + virtual bool filterTextFlags(const SkPaint& paint, TextFlags*); /** * Called with the correct matrix and clip before this device is drawn @@ -161,24 +178,15 @@ public: virtual void gainFocus(SkCanvas*, const SkMatrix&, const SkRegion&, const SkClipStack&) {} - /** Causes any deferred drawing to the device to be completed. - */ - virtual void flush() {} - - /** - * Copy the pixels from the device into bitmap. Returns true on success. - * If false is returned, then the bitmap parameter is left unchanged. - * The bitmap parameter is treated as output-only, and will be completely - * overwritten (if the method returns true). + /** Clears the entire device to the specified color (including alpha). + * Ignores the clip. */ - virtual bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap); + virtual void clear(SkColor color); /** - * Similar to draw sprite, this method will copy the pixels in bitmap onto - * the device, with the top/left corner specified by (x, y). The pixel - * values in the device are completely replaced: there is no blending. + * Deprecated name for clear. */ - virtual void writePixels(const SkBitmap& bitmap, int x, int y); + void eraseColor(SkColor eraseColor) { this->clear(eraseColor); } /** These are called inside the per-device-layer loop for each draw call. When these are called, we have already applied any saveLayer operations, @@ -210,6 +218,10 @@ public: const SkMatrix& matrix, const SkPaint& paint); virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap, int x, int y, const SkPaint& paint); + /** + * Does not handle text decoration. + * Decorations (underline and stike-thru) will be handled by SkCanvas. + */ virtual void drawText(const SkDraw&, const void* text, size_t len, SkScalar x, SkScalar y, const SkPaint& paint); virtual void drawPosText(const SkDraw&, const void* text, size_t len, @@ -218,7 +230,7 @@ public: virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len, const SkPath& path, const SkMatrix* matrix, const SkPaint& paint); -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID virtual void drawPosTextOnPath(const SkDraw& draw, const void* text, size_t len, const SkPoint pos[], const SkPaint& paint, const SkPath& path, const SkMatrix* matrix); @@ -228,35 +240,44 @@ public: const SkColor colors[], SkXfermode* xmode, const uint16_t indices[], int indexCount, const SkPaint& paint); + /** The SkDevice passed will be an SkDevice which was returned by a call to + onCreateCompatibleDevice on this device with kSaveLayer_Usage. + */ virtual void drawDevice(const SkDraw&, SkDevice*, int x, int y, const SkPaint&); - /////////////////////////////////////////////////////////////////////////// - - SkMetaData& getMetaData(); - - struct TextFlags { - uint32_t fFlags; // SkPaint::getFlags() - SkPaint::Hinting fHinting; - }; - /** - * Device may filter the text flags for drawing text here. If it wants to - * make a change to the specified values, it should write them into the - * textflags parameter (output) and return true. If the paint is fine as - * is, then ignore the textflags parameter and return false. + * On success (returns true), copy the device pixels into the bitmap. + * On failure, the bitmap parameter is left unchanged and false is + * returned. * - * The baseclass SkDevice filters based on its depth and blitters. + * The device's pixels are converted to the bitmap's config. The only + * supported config is kARGB_8888_Config, though this is likely to be + * relaxed in the future. The meaning of config kARGB_8888_Config is + * modified by the enum param config8888. The default value interprets + * kARGB_8888_Config as SkPMColor + * + * If the bitmap has pixels already allocated, the device pixels will be + * written there. If not, bitmap->allocPixels() will be called + * automatically. If the bitmap is backed by a texture readPixels will + * fail. + * + * The actual pixels written is the intersection of the device's bounds, + * and the rectangle formed by the bitmap's width,height and the specified + * x,y. If bitmap pixels extend outside of that intersection, they will not + * be modified. + * + * Other failure conditions: + * * If the device is not a raster device (e.g. PDF) then readPixels will + * fail. + * * If bitmap is texture-backed then readPixels will fail. (This may be + * relaxed in the future.) */ - virtual bool filterTextFlags(const SkPaint& paint, TextFlags*); + bool readPixels(SkBitmap* bitmap, + int x, int y, + SkCanvas::Config8888 config8888); -protected: - /** - * subclasses must override this to return a new (or ref'd) instance of - * a device factory that will create this subclass of device. This value - * is cached, so it should get called at most once for a given instance. - */ - virtual SkDeviceFactory* onNewDeviceFactory(); + /////////////////////////////////////////////////////////////////////////// /** Update as needed the pixel value in the bitmap, so that the caller can access the pixels directly. Note: only the pixels field should be altered. The config/width/height/rowbytes @@ -270,18 +291,76 @@ protected: fBitmap.setPixelRef(pr, offset); return pr; } + + /** + * Implements readPixels API. The caller will ensure that: + * 1. bitmap has pixel config kARGB_8888_Config. + * 2. bitmap has pixels. + * 3. The rectangle (x, y, x + bitmap->width(), y + bitmap->height()) is + * contained in the device bounds. + */ + virtual bool onReadPixels(const SkBitmap& bitmap, + int x, int y, + SkCanvas::Config8888 config8888); + + /** Called when this device is installed into a Canvas. Balanaced by a call + to unlockPixels() when the device is removed from a Canvas. + */ + virtual void lockPixels(); + virtual void unlockPixels(); + + /** + * Returns true if the device allows processing of this imagefilter. If + * false is returned, then the filter is ignored. This may happen for + * some subclasses that do not support pixel manipulations after drawing + * has occurred (e.g. printing). The default implementation returns true. + */ + virtual bool allowImageFilter(SkImageFilter*); + + /** + * Override and return true for filters that the device handles + * intrinsically. Returning false means call the filter. + * Default impl returns false. This will only be called if allowImageFilter() + * returned true. + */ + virtual bool filterImage(SkImageFilter*, const SkBitmap& src, + const SkMatrix& ctm, + SkBitmap* result, SkIPoint* offset); + + // This is equal kBGRA_Premul_Config8888 or kRGBA_Premul_Config8888 if + // either is identical to kNative_Premul_Config8888. Otherwise, -1. + static const SkCanvas::Config8888 kPMColorAlias; private: friend class SkCanvas; + friend struct DeviceCM; //for setMatrixClip + friend class SkDraw; + friend class SkDrawIter; + friend class SkDeviceFilteredPaint; + friend class DeviceImageFilterProxy; + // just called by SkCanvas when built as a layer void setOrigin(int x, int y) { fOrigin.set(x, y); } + // just called by SkCanvas for saveLayer + SkDevice* createCompatibleDeviceForSaveLayer(SkBitmap::Config config, + int width, int height, + bool isOpaque); + + /** + * Subclasses should override this to implement createCompatibleDevice. + */ + virtual SkDevice* onCreateCompatibleDevice(SkBitmap::Config config, + int width, int height, + bool isOpaque, + Usage usage); + + /** Causes any deferred drawing to the device to be completed. + */ + virtual void flush() {} - SkCanvas* fCanvas; SkBitmap fBitmap; SkIPoint fOrigin; SkMetaData* fMetaData; - - SkDeviceFactory* fCachedDeviceFactory; }; #endif diff --git a/include/core/SkDither.h b/include/core/SkDither.h index 5b2552d..692c7e4 100644 --- a/include/core/SkDither.h +++ b/include/core/SkDither.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDither_DEFINED #define SkDither_DEFINED diff --git a/include/core/SkDraw.h b/include/core/SkDraw.h index b751be0..8c659c2 100644 --- a/include/core/SkDraw.h +++ b/include/core/SkDraw.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDraw_DEFINED #define SkDraw_DEFINED @@ -30,6 +23,7 @@ class SkClipStack; class SkDevice; class SkPath; class SkRegion; +class SkRasterClip; struct SkDrawProcs; class SkDraw { @@ -61,7 +55,7 @@ public: int scalarsPerPosition, const SkPaint& paint) const; void drawTextOnPath(const char text[], size_t byteLength, const SkPath&, const SkMatrix*, const SkPaint&) const; -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID void drawPosTextOnPath(const char text[], size_t byteLength, const SkPoint pos[], const SkPaint& paint, const SkPath& path, const SkMatrix* matrix) const; @@ -112,7 +106,8 @@ private: public: const SkBitmap* fBitmap; // required const SkMatrix* fMatrix; // required - const SkRegion* fClip; // required + const SkRegion* fClip; // DEPRECATED + const SkRasterClip* fRC; // required const SkClipStack* fClipStack; // optional SkDevice* fDevice; // optional @@ -154,6 +149,7 @@ private: const SkPath* fPath; // returned in next SkScalar fXPos; // accumulated xpos, returned in next SkAutoKern fAutoKern; + int fXYIndex; // cache for horizontal -vs- vertical text }; #endif diff --git a/include/core/SkDrawFilter.h b/include/core/SkDrawFilter.h index c8af187..303b80e 100644 --- a/include/core/SkDrawFilter.h +++ b/include/core/SkDrawFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2011 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDrawFilter_DEFINED #define SkDrawFilter_DEFINED diff --git a/include/core/SkDrawLooper.h b/include/core/SkDrawLooper.h index 3830b4a..e8265db 100644 --- a/include/core/SkDrawLooper.h +++ b/include/core/SkDrawLooper.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2011 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDrawLooper_DEFINED #define SkDrawLooper_DEFINED diff --git a/include/core/SkEdgeClipper.h b/include/core/SkEdgeClipper.h index 6720b9c..a7eedd5 100644 --- a/include/core/SkEdgeClipper.h +++ b/include/core/SkEdgeClipper.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2009 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkEdgeClipper_DEFINED #define SkEdgeClipper_DEFINED diff --git a/include/core/SkEmptyShader.h b/include/core/SkEmptyShader.h new file mode 100644 index 0000000..bf270bf --- /dev/null +++ b/include/core/SkEmptyShader.h @@ -0,0 +1,43 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef SkEmptyShader_DEFINED +#define SkEmptyShader_DEFINED + +#include "SkShader.h" + +/** + * \class SkEmptyShader + * A Shader that always draws nothing. Its setContext always returns false, + * so it never expects that its shadeSpan() methods will get called. + */ +class SK_API SkEmptyShader : public SkShader { +public: + SkEmptyShader() {} + + virtual uint32_t getFlags() SK_OVERRIDE; + virtual uint8_t getSpan16Alpha() const SK_OVERRIDE; + virtual bool setContext(const SkBitmap&, const SkPaint&, + const SkMatrix&) SK_OVERRIDE; + virtual void shadeSpan(int x, int y, SkPMColor span[], int count) SK_OVERRIDE; + virtual void shadeSpan16(int x, int y, uint16_t span[], int count) SK_OVERRIDE; + virtual void shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) SK_OVERRIDE; + +protected: + SkEmptyShader(SkFlattenableReadBuffer&); + + virtual Factory getFactory() SK_OVERRIDE; + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + +private: + typedef SkShader INHERITED; +}; + +#endif diff --git a/include/core/SkEndian.h b/include/core/SkEndian.h index a72dfe3..3eb67da 100644 --- a/include/core/SkEndian.h +++ b/include/core/SkEndian.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkEndian_DEFINED #define SkEndian_DEFINED @@ -87,6 +80,19 @@ static inline void SkEndianSwap32s(uint32_t array[], int count) { #define SkEndian_SwapLE32(n) SkEndianSwap32(n) #endif +// When a bytestream is embedded in a 32-bit word, how far we need to +// shift the word to extract each byte from the low 8 bits by anding with 0xff. +#ifdef SK_CPU_LENDIAN + #define SkEndian_Byte0Shift 0 + #define SkEndian_Byte1Shift 8 + #define SkEndian_Byte2Shift 16 + #define SkEndian_Byte3Shift 24 +#else // SK_CPU_BENDIAN + #define SkEndian_Byte0Shift 24 + #define SkEndian_Byte1Shift 16 + #define SkEndian_Byte2Shift 8 + #define SkEndian_Byte3Shift 0 +#endif #endif diff --git a/include/core/SkFDot6.h b/include/core/SkFDot6.h index 9d56116..aa58857 100644 --- a/include/core/SkFDot6.h +++ b/include/core/SkFDot6.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFDot6_DEFINED #define SkFDot6_DEFINED diff --git a/include/core/SkFixed.h b/include/core/SkFixed.h index 8b56c50..0af5d9d 100644 --- a/include/core/SkFixed.h +++ b/include/core/SkFixed.h @@ -1,23 +1,16 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFixed_DEFINED #define SkFixed_DEFINED -#include "SkMath.h" +#include "SkTypes.h" /** \file SkFixed.h @@ -103,17 +96,23 @@ inline SkFixed SkFixedFraction(SkFixed x) /** Converts a SkFract to a SkFixed */ #define SkFractToFixed(x) ((x) >> 14) -/** Round a SkFixed to an integer -*/ -#define SkFixedRound(x) (((x) + SK_FixedHalf) >> 16) -#define SkFixedCeil(x) (((x) + SK_Fixed1 - 1) >> 16) -#define SkFixedFloor(x) ((x) >> 16) + +#define SkFixedRoundToInt(x) (((x) + SK_FixedHalf) >> 16) +#define SkFixedCeilToInt(x) (((x) + SK_Fixed1 - 1) >> 16) +#define SkFixedFloorToInt(x) ((x) >> 16) + +#define SkFixedRoundToFixed(x) (((x) + SK_FixedHalf) & 0xFFFF0000) +#define SkFixedCeilToFixed(x) (((x) + SK_Fixed1 - 1) & 0xFFFF0000) +#define SkFixedFloorToFixed(x) ((x) & 0xFFFF0000) + +// DEPRECATED +#define SkFixedFloor(x) SkFixedFloorToInt(x) +#define SkFixedCeil(x) SkFixedCeilToInt(x) +#define SkFixedRound(x) SkFixedRoundToInt(x) + #define SkFixedAbs(x) SkAbs32(x) #define SkFixedAve(a, b) (((a) + (b)) >> 1) -// The same as SkIntToFixed(SkFixedFloor(x)) -#define SkFixedFloorToFixed(x) ((x) & ~0xFFFF) - SkFixed SkFixedMul_portable(SkFixed, SkFixed); SkFract SkFractMul_portable(SkFract, SkFract); inline SkFixed SkFixedSquare_portable(SkFixed value) diff --git a/include/core/SkFlate.h b/include/core/SkFlate.h index b606742..c111de0 100644 --- a/include/core/SkFlate.h +++ b/include/core/SkFlate.h @@ -1,25 +1,19 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2010 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFlate_DEFINED #define SkFlate_DEFINED #include "SkTypes.h" -class SkDynamicMemoryWStream; +class SkData; +class SkWStream; class SkStream; /** \class SkFlate @@ -31,15 +25,28 @@ public: */ static bool HaveFlate(); - /** Use the flate compression algorithm to compress the data in src, - putting the result into dst. Returns false if an error occurs. + /** + * Use the flate compression algorithm to compress the data in src, + * putting the result into dst. Returns false if an error occurs. */ - static bool Deflate(SkStream* src, SkDynamicMemoryWStream* dst); - + static bool Deflate(SkStream* src, SkWStream* dst); + + /** + * Use the flate compression algorithm to compress the data in src, + * putting the result into dst. Returns false if an error occurs. + */ + static bool Deflate(const void* src, size_t len, SkWStream* dst); + + /** + * Use the flate compression algorithm to compress the data, + * putting the result into dst. Returns false if an error occurs. + */ + static bool Deflate(const SkData*, SkWStream* dst); + /** Use the flate compression algorithm to decompress the data in src, putting the result into dst. Returns false if an error occurs. */ - static bool Inflate(SkStream* src, SkDynamicMemoryWStream* dst); + static bool Inflate(SkStream* src, SkWStream* dst); }; #endif diff --git a/include/core/SkFlattenable.h b/include/core/SkFlattenable.h index 03bcab8..a66638e 100644 --- a/include/core/SkFlattenable.h +++ b/include/core/SkFlattenable.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFlattenable_DEFINED #define SkFlattenable_DEFINED @@ -27,6 +20,40 @@ class SkFlattenableReadBuffer; class SkFlattenableWriteBuffer; class SkString; +#if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS + +#define SK_DECLARE_FLATTENABLE_REGISTRAR() + +#define SK_DEFINE_FLATTENABLE_REGISTRAR(flattenable) \ + static SkFlattenable::Registrar g##flattenable##Reg(#flattenable, \ + flattenable::CreateProc); + +#define SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(flattenable) +#define SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(flattenable) \ + static SkFlattenable::Registrar g##flattenable##Reg(#flattenable, \ + flattenable::CreateProc); +#define SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END + +#else + +#define SK_DECLARE_FLATTENABLE_REGISTRAR() static void Init(); + +#define SK_DEFINE_FLATTENABLE_REGISTRAR(flattenable) \ + void flattenable::Init() { \ + SkFlattenable::Registrar(#flattenable, CreateProc); \ + } + +#define SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(flattenable) \ + void flattenable::Init() { + +#define SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(flattenable) \ + SkFlattenable::Registrar(#flattenable, flattenable::CreateProc); + +#define SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END \ + } + +#endif + /** \class SkFlattenable SkFlattenable is the base class for objects that need to be flattened @@ -68,6 +95,13 @@ public: protected: SkFlattenable(SkFlattenableReadBuffer&) {} + +private: +#if !SK_ALLOW_STATIC_GLOBAL_INITIALIZERS + static void InitializeFlattenables(); +#endif + + friend class SkGraphics; }; // helpers for matrix and region @@ -100,11 +134,27 @@ public: fTFArray = array; fTFCount = count; } - + + /** + * Call this with a pre-loaded array of Factories, in the same order as + * were created/written by the writer. SkPicture uses this. + */ void setFactoryPlayback(SkFlattenable::Factory array[], int count) { + fFactoryTDArray = NULL; fFactoryArray = array; fFactoryCount = count; } + + /** + * Call this with an initially empty array, so the reader can cache each + * factory it sees by name. Used by the pipe code in conjunction with + * the writer's kInlineFactoryNames_Flag. + */ + void setFactoryArray(SkTDArray<SkFlattenable::Factory>* array) { + fFactoryTDArray = array; + fFactoryArray = NULL; + fFactoryCount = 0; + } SkTypeface* readTypeface(); SkRefCnt* readRefCnt(); @@ -118,6 +168,7 @@ private: SkTypeface** fTFArray; int fTFCount; + SkTDArray<SkFlattenable::Factory>* fFactoryTDArray; SkFlattenable::Factory* fFactoryArray; int fFactoryCount; @@ -165,12 +216,22 @@ public: SkFactorySet* setFactoryRecorder(SkFactorySet*); enum Flags { - kCrossProcess_Flag = 0x01 + kCrossProcess_Flag = 0x01, + /** + * Instructs the writer to inline Factory names as there are seen the + * first time (after that we store an index). The pipe code uses this. + */ + kInlineFactoryNames_Flag = 0x02, }; - Flags getFlags() const { return fFlags; } + Flags getFlags() const { return (Flags)fFlags; } void setFlags(Flags flags) { fFlags = flags; } - bool isCrossProcess() const { return (fFlags & kCrossProcess_Flag) != 0; } + bool isCrossProcess() const { + return SkToBool(fFlags & kCrossProcess_Flag); + } + bool inlineFactoryNames() const { + return SkToBool(fFlags & kInlineFactoryNames_Flag); + } bool persistBitmapPixels() const { return (fFlags & kCrossProcess_Flag) != 0; @@ -179,10 +240,10 @@ public: bool persistTypeface() const { return (fFlags & kCrossProcess_Flag) != 0; } private: - Flags fFlags; - SkRefCntSet* fTFSet; - SkRefCntSet* fRCSet; - SkFactorySet* fFactorySet; + uint32_t fFlags; + SkRefCntSet* fTFSet; + SkRefCntSet* fRCSet; + SkFactorySet* fFactorySet; typedef SkWriter32 INHERITED; }; diff --git a/include/core/SkFloatBits.h b/include/core/SkFloatBits.h index 288f2d8..e6fc5b5 100644 --- a/include/core/SkFloatBits.h +++ b/include/core/SkFloatBits.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFloatBits_DEFINED #define SkFloatBits_DEFINED diff --git a/include/core/SkFloatingPoint.h b/include/core/SkFloatingPoint.h index 8c3bb83..ee91cd9 100644 --- a/include/core/SkFloatingPoint.h +++ b/include/core/SkFloatingPoint.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFloatingPoint_DEFINED #define SkFloatingPoint_DEFINED @@ -65,12 +58,24 @@ static inline float sk_float_copysign(float x, float y) { #define sk_float_acos(x) acosf(x) #define sk_float_asin(x) asinf(x) #endif - #define sk_float_atan2(y,x) atan2f(y,x) + #define sk_float_atan2(y,x) atan2f(y,x) #define sk_float_abs(x) fabsf(x) #define sk_float_mod(x,y) fmodf(x,y) #define sk_float_exp(x) expf(x) #define sk_float_log(x) logf(x) - #define sk_float_isNaN(x) _isnan(x) +#endif + +#ifdef SK_BUILD_FOR_WIN + #define sk_float_isfinite(x) _finite(x) + #define sk_float_isnan(x) _isnan(x) + static inline int sk_float_isinf(float x) { + int32_t bits = SkFloat2Bits(x); + return (bits << 1) == (0xFF << 24); + } +#else + #define sk_float_isfinite(x) isfinite(x) + #define sk_float_isnan(x) isnan(x) + #define sk_float_isinf(x) isinf(x) #endif #ifdef SK_USE_FLOATBITS diff --git a/include/core/SkFontHost.h b/include/core/SkFontHost.h index e20ea05..c549519 100644 --- a/include/core/SkFontHost.h +++ b/include/core/SkFontHost.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFontHost_DEFINED #define SkFontHost_DEFINED @@ -31,7 +24,7 @@ typedef uint32_t SkFontTableTag; This class is ported to each environment. It is responsible for bridging the gap between the (sort of) abstract class SkTypeface and the platform-specific implementation that provides access to font files. - + One basic task is for each create (subclass of) SkTypeface, the FontHost is resonsible for assigning a uniqueID. The ID should be unique for the underlying font file/data, not unique per typeface instance. Thus it is @@ -43,7 +36,7 @@ typedef uint32_t SkFontTableTag; returned). Either way, the fontID for those instance(s) will be the same. In addition, the fontID should never be set to 0. That value is used as a sentinel to indicate no-font-id. - + The major aspects are: 1) Given either a name/style, return a subclass of SkTypeface that references the closest matching font available on the host system. @@ -72,17 +65,17 @@ public: /** Return a new typeface given the data buffer. If the data does not represent a valid font, returns null. - + If a typeface instance is returned, the caller is responsible for calling unref() on the typeface when they are finished with it. - + The returned typeface may or may not have called ref() on the stream parameter. If the typeface has not called ref(), then it may have made a copy of the releveant data. In either case, the caller is still - responsible for its refcnt ownership of the stream. + responsible for its refcnt ownership of the stream. */ static SkTypeface* CreateTypefaceFromStream(SkStream*); - + /** Return a new typeface from the specified file path. If the file does not represent a valid font, this returns null. If a typeface is returned, the caller is responsible for calling unref() when it is no longer used. @@ -90,13 +83,13 @@ public: static SkTypeface* CreateTypefaceFromFile(const char path[]); /////////////////////////////////////////////////////////////////////////// - + /** Returns true if the specified unique ID matches an existing font. Returning false is similar to calling OpenStream with an invalid ID, which will return NULL in that case. */ static bool ValidFontID(SkFontID uniqueID); - + /** Return a new stream to read the font data, or null if the uniqueID does not match an existing typeface. .The caller must call stream->unref() when it is finished reading the data. @@ -145,7 +138,7 @@ public: static SkTypeface* Deserialize(SkStream*); /////////////////////////////////////////////////////////////////////////// - + /** Return a subclass of SkScalarContext */ static SkScalerContext* CreateScalerContext(const SkDescriptor* desc); @@ -188,10 +181,17 @@ public: names, etc.) should be populated. @return The returned object has already been referenced. NULL is returned if the font is not found. + @param glyphIDs For per-glyph info, specify subset of the font by + giving glyph ids. Each integer represents a glyph + id. Passing NULL means all glyphs in the font. + @param glyphIDsCount Number of elements in subsetGlyphIds. Ignored if + glyphIDs is NULL. */ static SkAdvancedTypefaceMetrics* GetAdvancedTypefaceMetrics( SkFontID fontID, - SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo); + SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo, + const uint32_t* glyphIDs, + uint32_t glyphIDsCount); /** Return the number of tables in the font */ @@ -206,7 +206,7 @@ public: /** Given a table tag, return the size of its contents, or 0 if not present */ static size_t GetTableSize(SkFontID, SkFontTableTag); - + /** Copy the contents of a table into data (allocated by the caller). Note that the contents of the table will be in their native endian order (which for most truetype tables is big endian). If the table tag is @@ -232,20 +232,9 @@ public: /////////////////////////////////////////////////////////////////////////// - /** Return the number of bytes (approx) that should be purged from the font - cache. The input parameter is the cache's estimate of how much as been - allocated by the cache so far. - To purge (basically) everything, return the input parameter. - To purge nothing, return 0 - */ - static size_t ShouldPurgeFontCache(size_t sizeAllocatedSoFar); + /** DEPRECATED -- only called by SkFontHost_FreeType internally - /** Return SkScalerContext gamma flag, or 0, based on the paint that will be - used to draw something with antialiasing. - */ - static int ComputeGammaFlag(const SkPaint& paint); - - /** Return NULL or a pointer to 256 bytes for the black (table[0]) and + Return NULL or a pointer to 256 bytes for the black (table[0]) and white (table[1]) gamma tables. */ static void GetGammaTables(const uint8_t* tables[2]); @@ -286,7 +275,7 @@ public: static void SetSubpixelOrder(LCDOrder order); static LCDOrder GetSubpixelOrder(); -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID /////////////////////////////////////////////////////////////////////////// /** @@ -297,7 +286,14 @@ public: */ static uint32_t GetUnitsPerEm(SkFontID fontID); #endif + + /** If Skia is running in a constrained environment and the typeface + implementation is handle based, the typeface data may become + unavailable asynchronously. If a font host or scaler context method is + unable to access font data, it may call this function as a request to + make the handle contained in the typeface useable. + */ + static void EnsureTypefaceAccessible(const SkTypeface& typeface); }; #endif - diff --git a/include/core/SkGeometry.h b/include/core/SkGeometry.h index 000ca73..26f27ba 100644 --- a/include/core/SkGeometry.h +++ b/include/core/SkGeometry.h @@ -1,19 +1,11 @@ -/* libs/graphics/sgl/SkGeometry.h -** -** Copyright 2006, The Android Open Source Project -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ + +/* + * Copyright 2006 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkGeometry_DEFINED #define SkGeometry_DEFINED @@ -113,7 +105,11 @@ void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* locOrNull, dst[0..3] and dst[3..6] */ void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t); -void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], const SkScalar t[], +/** Given a src cubic bezier, chop it at the specified t values, + where 0 < t < 1, and return the new cubics in dst: + dst[0..3],dst[3..6],...,dst[3*t_count..3*(t_count+1)] +*/ +void SkChopCubicAt(const SkPoint src[4], SkPoint dst[], const SkScalar t[], int t_count); /** Given a src cubic bezier, chop it at the specified t == 1/2, @@ -149,8 +145,9 @@ int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]); */ int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[2]); -/** Return 1 for no chop, or 2 for having chopped the cubic at its - inflection point. +/** Return 1 for no chop, 2 for having chopped the cubic at a single + inflection point, 3 for having chopped at 2 inflection points. + dst will hold the resulting 1, 2, or 3 cubics. */ int SkChopCubicAtInflections(const SkPoint src[4], SkPoint dst[10]); diff --git a/include/core/SkGlobals.h b/include/core/SkGlobals.h deleted file mode 100644 index 8e28290..0000000 --- a/include/core/SkGlobals.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SkGlobals_DEFINED -#define SkGlobals_DEFINED - -#include "SkThread.h" - -class SkGlobals { -public: - class Rec { - public: - virtual ~Rec(); - private: - Rec* fNext; - uint32_t fTag; - - friend class SkGlobals; - }; - - /** Look for a matching Rec for the specified tag. If one is found, return it. - If one is not found, if create_proc is null, return null, else - call the proc, and if it returns a Rec, add it to the global list - and return it. - - create_proc can NOT call back into SkGlobals::Find (it would deadlock) - */ - static Rec* Find(uint32_t tag, Rec* (*create_proc)()); - /** Helper for Find, when you want to assert that the Rec is already in the list - */ - static Rec* Get(uint32_t tag) - { - Rec* rec = SkGlobals::Find(tag, NULL); - SkASSERT(rec); - return rec; - } - - // used by porting layer - struct BootStrap { - SkMutex fMutex; - Rec* fHead; - }; - -private: - static void Init(); - static void Term(); - friend class SkGraphics; - - // This last function is implemented in the porting layer - static BootStrap& GetBootStrap(); -}; - -#endif - diff --git a/include/core/SkGraphics.h b/include/core/SkGraphics.h index 25c926f..c89758b 100644 --- a/include/core/SkGraphics.h +++ b/include/core/SkGraphics.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkGraphics_DEFINED #define SkGraphics_DEFINED @@ -21,24 +14,57 @@ class SkGraphics { public: + /** + * Call this at process initialization time if your environment does not + * permit static global initializers that execute code. Note that + * Init() is not thread-safe. + */ static void Init(); - static void Term(); - /** Return the (approximate) number of bytes used by the font cache. - */ - static size_t GetFontCacheUsed(); - - /** Attempt to purge the font cache until <= the specified amount remains - in the cache. Specifying 0 will attempt to purge the entire cache. - Returns true if some amount was purged from the font cache. - */ - static bool SetFontCacheUsed(size_t usageInBytes); + /** + * Call this to release any memory held privately, such as the font cache. + */ + static void Term(); - /** Return the version numbers for the library. If the parameter is not - null, it is set to the version number. + /** + * Return the version numbers for the library. If the parameter is not + * null, it is set to the version number. */ static void GetVersion(int32_t* major, int32_t* minor, int32_t* patch); + /** + * Return the max number of bytes that should be used by the font cache. + * If the cache needs to allocate more, it will purge previous entries. + * This max can be changed by calling SetFontCacheLimit(). + */ + static size_t GetFontCacheLimit(); + + /** + * Specify the max number of bytes that should be used by the font cache. + * If the cache needs to allocate more, it will purge previous entries. + * + * This function returns the previous setting, as if GetFontCacheLimit() + * had be called before the new limit was set. + */ + static size_t SetFontCacheLimit(size_t bytes); + + /** + * For debugging purposes, this will attempt to purge the font cache. It + * does not change the limit, but will cause subsequent font measures and + * draws to be recreated, since they will no longer be in the cache. + */ + static void PurgeFontCache(); + + /** + * Applications with command line options may pass optional state, such + * as cache sizes, here, for instance: + * font-cache-limit=12345678 + * + * The flags format is name=value[;name=value...] with no spaces. + * This format is subject to change. + */ + static void SetFlags(const char* flags); + private: /** This is automatically called by SkGraphics::Init(), and must be implemented by the host OS. This allows the host OS to register a callback diff --git a/include/core/SkImageFilter.h b/include/core/SkImageFilter.h new file mode 100644 index 0000000..22b9569 --- /dev/null +++ b/include/core/SkImageFilter.h @@ -0,0 +1,97 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkImageFilter_DEFINED +#define SkImageFilter_DEFINED + +#include "SkFlattenable.h" + +class SkBitmap; +class SkDevice; +class SkMatrix; +struct SkPoint; + +/** + * Experimental. + * + * Base class for image filters. If one is installed in the paint, then + * all drawing occurs as usual, but it is as if the drawing happened into an + * offscreen (before the xfermode is applied). This offscreen bitmap will + * then be handed to the imagefilter, who in turn creates a new bitmap which + * is what will finally be drawn to the device (using the original xfermode). + * + * THIS SIGNATURE IS TEMPORARY + * + * There are several weaknesses in this function signature: + * 1. Does not expose the destination/target device, so filters that can draw + * directly to it are unable to take advantage of that optimization. + * 2. Does not expose a way to create a "compabitible" image (i.e. gpu -> gpu) + * 3. As with #1, the filter is unable to "read" the dest (which would be slow) + * + * Therefore, we should not create any real dependencies on this API yet -- it + * is being checked in as a check-point so we can explore these and other + * considerations. + */ +class SK_API SkImageFilter : public SkFlattenable { +public: + class Proxy { + public: + virtual SkDevice* createDevice(int width, int height) = 0; + + // returns true if the proxy handled the filter itself. if this returns + // false then the filter's code will be called. + virtual bool filterImage(SkImageFilter*, const SkBitmap& src, + const SkMatrix& ctm, + SkBitmap* result, SkIPoint* offset) = 0; + virtual ~Proxy() {}; + }; + + /** + * Request a new (result) image to be created from the src image. + * If the src has no pixels (isNull()) then the request just wants to + * receive the config and width/height of the result. + * + * The matrix is the current matrix on the canvas. + * + * Offset is the amount to translate the resulting image relative to the + * src when it is drawn. + * + * If the result image cannot be created, return false, in which case both + * the result and offset parameters will be ignored by the caller. + */ + bool filterImage(Proxy*, const SkBitmap& src, const SkMatrix& ctm, + SkBitmap* result, SkIPoint* offset); + + /** + * Given the src bounds of an image, this returns the bounds of the result + * image after the filter has been applied. + */ + bool filterBounds(const SkIRect& src, const SkMatrix& ctm, SkIRect* dst); + + /** + * Experimental. + * + * If the filter can be expressed as a gaussian-blur, return true and + * set the sigma to the values for horizontal and vertical. + */ + virtual bool asABlur(SkSize* sigma) const; + +protected: + SkImageFilter() {} + explicit SkImageFilter(SkFlattenableReadBuffer& rb) : INHERITED(rb) {} + + // Default impl returns false + virtual bool onFilterImage(Proxy*, const SkBitmap& src, const SkMatrix&, + SkBitmap* result, SkIPoint* offset); + // Default impl copies src into dst and returns true + virtual bool onFilterBounds(const SkIRect&, const SkMatrix&, SkIRect*); + +private: + typedef SkFlattenable INHERITED; +}; + +#endif diff --git a/include/core/SkLineClipper.h b/include/core/SkLineClipper.h index 4c23781..1958395 100644 --- a/include/core/SkLineClipper.h +++ b/include/core/SkLineClipper.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkLineClipper_DEFINED #define SkLineClipper_DEFINED diff --git a/include/core/SkMMapStream.h b/include/core/SkMMapStream.h index be063bd..19ba634 100644 --- a/include/core/SkMMapStream.h +++ b/include/core/SkMMapStream.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMMapStream_DEFINED #define SkMMapStream_DEFINED @@ -26,7 +19,6 @@ public: virtual void setMemory(const void* data, size_t length, bool); private: - int fFildes; void* fAddr; size_t fSize; diff --git a/include/core/SkMallocPixelRef.h b/include/core/SkMallocPixelRef.h index edaab94..2ceb826 100644 --- a/include/core/SkMallocPixelRef.h +++ b/include/core/SkMallocPixelRef.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMallocPixelRef_DEFINED #define SkMallocPixelRef_DEFINED @@ -44,6 +37,7 @@ public: return SkNEW_ARGS(SkMallocPixelRef, (buffer)); } + SK_DECLARE_PIXEL_REF_REGISTRAR() protected: // overrides from SkPixelRef virtual void* onLockPixels(SkColorTable**); diff --git a/include/core/SkMask.h b/include/core/SkMask.h index f437622..3f9a114 100644 --- a/include/core/SkMask.h +++ b/include/core/SkMask.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMask_DEFINED #define SkMask_DEFINED @@ -28,30 +21,13 @@ struct SkMask { kBW_Format, //!< 1bit per pixel mask (e.g. monochrome) kA8_Format, //!< 8bits per pixel mask (e.g. antialiasing) k3D_Format, //!< 3 8bit per pixl planes: alpha, mul, add - - /* The LCD formats look like this in memory: - - First, there's an A8 plane which contains the average alpha value for - each pixel. Because of this, the LCD formats can be passed directly - to functions which expect an A8 and everything will just work. - - After that in memory, there's a bitmap of 32-bit values which have - been RGB order corrected for the current screen (based on the - settings in SkFontHost at the time of renderering). The alpha value - for each pixel is the maximum of the three alpha values. - - kHorizontalLCD_Format has an extra column of pixels on the left and right - edges. kVerticalLCD_Format has an extra row at the top and bottom. - */ - - kHorizontalLCD_Format, //!< 4 bytes/pixel: a/r/g/b - kVerticalLCD_Format, //!< 4 bytes/pixel: a/r/g/b kARGB32_Format, //!< SkPMColor - kLCD16_Format //!< 565 alpha for r/g/b + kLCD16_Format, //!< 565 alpha for r/g/b + kLCD32_Format //!< 888 alpha for r/g/b }; enum { - kCountMaskFormats = kVerticalLCD_Format + 1 + kCountMaskFormats = kLCD32_Format + 1 }; uint8_t* fImage; @@ -80,7 +56,7 @@ struct SkMask { x,y are in the same coordiate space as fBounds. */ uint8_t* getAddr1(int x, int y) const { - SkASSERT(fFormat == kBW_Format); + SkASSERT(kBW_Format == fFormat); SkASSERT(fBounds.contains(x, y)); SkASSERT(fImage != NULL); return fImage + ((x - fBounds.fLeft) >> 3) + (y - fBounds.fTop) * fRowBytes; @@ -90,8 +66,8 @@ struct SkMask { Asserts that the mask is kA8_Format, and that x,y are in range. x,y are in the same coordiate space as fBounds. */ - uint8_t* getAddr(int x, int y) const { - SkASSERT(fFormat != kBW_Format); + uint8_t* getAddr8(int x, int y) const { + SkASSERT(kA8_Format == fFormat); SkASSERT(fBounds.contains(x, y)); SkASSERT(fImage != NULL); return fImage + x - fBounds.fLeft + (y - fBounds.fTop) * fRowBytes; @@ -110,28 +86,32 @@ struct SkMask { return row + (x - fBounds.fLeft); } - /** Return an address into the 32-bit plane of an LCD or VerticalLCD mask - for the given position. - */ - const uint32_t* getAddrLCD(int x, int y) const { - SkASSERT(fFormat == kHorizontalLCD_Format || fFormat == kVerticalLCD_Format); + /** + * Return the address of the specified 32bit mask. In the debug build, + * this asserts that the mask's format is kLCD32_Format, and that (x,y) + * are contained in the mask's fBounds. + */ + uint32_t* getAddrLCD32(int x, int y) const { + SkASSERT(kLCD32_Format == fFormat); + SkASSERT(fBounds.contains(x, y)); SkASSERT(fImage != NULL); - - return reinterpret_cast<const uint32_t*>(fImage + SkAlign4(fRowBytes * fBounds.height())) + - x - fBounds.fLeft + (y - fBounds.fTop) * rowWordsLCD(); + uint32_t* row = (uint32_t*)(fImage + (y - fBounds.fTop) * fRowBytes); + return row + (x - fBounds.fLeft); } - /** Return the number of 32-bit words in a row of the 32-bit plane of an - LCD or VerticalLCD mask. - */ - unsigned rowWordsLCD() const { - SkASSERT(fFormat == kHorizontalLCD_Format || fFormat == kVerticalLCD_Format); - if (fFormat == kHorizontalLCD_Format) { - return fBounds.width() + 2; - } else { - return fBounds.width(); - } - } + /** + * Returns the address of the specified pixel, computing the pixel-size + * at runtime based on the mask format. This will be slightly slower than + * using one of the routines where the format is implied by the name + * e.g. getAddr8 or getAddrLCD32. + * + * x,y must be contained by the mask's bounds (this is asserted in the + * debug build, but not checked in the release build.) + * + * This should not be called with kBW_Format, as it will give unspecified + * results (and assert in the debug build). + */ + void* getAddr(int x, int y) const; static uint8_t* AllocImage(size_t bytes); static void FreeImage(void* image); @@ -141,10 +121,28 @@ struct SkMask { kJustRenderImage_CreateMode, //!< render into preallocate mask kComputeBoundsAndRenderImage_CreateMode //!< compute bounds, alloc image and render into it }; +}; + +/////////////////////////////////////////////////////////////////////////////// - static bool FormatIsLCD(Format fm) { - return kHorizontalLCD_Format == fm || kVerticalLCD_Format == fm; +/** + * \class SkAutoMaskImage + * + * Stack class used to manage the fImage buffer in a SkMask. + * When this object loses scope, the buffer is freed with SkMask::FreeImage(). + */ +class SkAutoMaskFreeImage { +public: + SkAutoMaskFreeImage(uint8_t* maskImage) { + fImage = maskImage; + } + + ~SkAutoMaskFreeImage() { + SkMask::FreeImage(fImage); } + +private: + uint8_t* fImage; }; #endif diff --git a/include/core/SkMaskFilter.h b/include/core/SkMaskFilter.h index 60dade9..2808de7 100644 --- a/include/core/SkMaskFilter.h +++ b/include/core/SkMaskFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMaskFilter_DEFINED #define SkMaskFilter_DEFINED @@ -24,7 +17,7 @@ class SkBlitter; class SkBounder; class SkMatrix; class SkPath; -class SkRegion; +class SkRasterClip; /** \class SkMaskFilter @@ -62,16 +55,30 @@ public: virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&, SkIPoint* margin); - /** Helper method that, given a path in device space, will rasterize it into a kA8_Format mask - and then call filterMask(). If this returns true, the specified blitter will be called - to render that mask. Returns false if filterMask() returned false. - This method is not exported to java. - */ - bool filterPath(const SkPath& devPath, const SkMatrix& devMatrix, - const SkRegion& devClip, SkBounder*, SkBlitter* blitter); - virtual void flatten(SkFlattenableWriteBuffer& ) {} + enum BlurType { + kNone_BlurType, //!< this maskfilter is not a blur + kNormal_BlurType, //!< fuzzy inside and outside + kSolid_BlurType, //!< solid inside, fuzzy outside + kOuter_BlurType, //!< nothing inside, fuzzy outside + kInner_BlurType, //!< fuzzy inside, nothing outside + }; + + struct BlurInfo { + SkScalar fRadius; + bool fIgnoreTransform; + bool fHighQuality; + }; + + /** + * Optional method for maskfilters that can be described as a blur. If so, + * they return the corresponding BlurType and set the fields in BlurInfo + * (if not null). If they cannot be described as a blur, they return + * kNone_BlurType and ignore the info parameter. + */ + virtual BlurType asABlur(BlurInfo*) const; + /** * The fast bounds function is used to enable the paint to be culled early * in the drawing pipeline. This function accepts the current bounds of the @@ -88,27 +95,17 @@ public: protected: // empty for now, but lets get our subclass to remember to init us for the future SkMaskFilter(SkFlattenableReadBuffer&) {} -}; -/** \class SkAutoMaskImage - - Stack class used to manage the fImage buffer in a SkMask. - When this object loses scope, the buffer is freed with SkMask::FreeImage(). -*/ -class SkAutoMaskImage { -public: - SkAutoMaskImage(SkMask* mask, bool alloc) { - if (alloc) { - mask->fImage = SkMask::AllocImage(mask->computeImageSize()); - } - fImage = mask->fImage; - } - - ~SkAutoMaskImage() { - SkMask::FreeImage(fImage); - } private: - uint8_t* fImage; + friend class SkDraw; + + /** Helper method that, given a path in device space, will rasterize it into a kA8_Format mask + and then call filterMask(). If this returns true, the specified blitter will be called + to render that mask. Returns false if filterMask() returned false. + This method is not exported to java. + */ + bool filterPath(const SkPath& devPath, const SkMatrix& devMatrix, + const SkRasterClip&, SkBounder*, SkBlitter* blitter); }; #endif diff --git a/include/core/SkMath.h b/include/core/SkMath.h index efe378a..5889103 100644 --- a/include/core/SkMath.h +++ b/include/core/SkMath.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMath_DEFINED #define SkMath_DEFINED diff --git a/include/core/SkMatrix.h b/include/core/SkMatrix.h index 480e077..8fdb818 100644 --- a/include/core/SkMatrix.h +++ b/include/core/SkMatrix.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMatrix_DEFINED #define SkMatrix_DEFINED @@ -21,6 +14,16 @@ class SkString; +#ifdef SK_SCALAR_IS_FLOAT + typedef SkScalar SkPersp; + #define SkScalarToPersp(x) (x) + #define SkPerspToScalar(x) (x) +#else + typedef SkFract SkPersp; + #define SkScalarToPersp(x) SkFixedToFract(x) + #define SkPerspToScalar(x) SkFractToFixed(x) +#endif + /** \class SkMatrix The SkMatrix class holds a 3x3 matrix for transforming coordinates. @@ -74,10 +77,11 @@ public: bool preservesAxisAlignment() const { return this->rectStaysRect(); } /** - * Returns true if the perspective contains perspective elements. + * Returns true if the matrix contains perspective elements. */ bool hasPerspective() const { - return SkToBool(this->getType() & kPerspective_Mask); + return SkToBool(this->getPerspectiveTypeMaskOnly() & + kPerspective_Mask); } enum { @@ -92,6 +96,18 @@ public: kMPersp2 }; + /** Affine arrays are in column major order + because that's how PDF and XPS like it. + */ + enum { + kAScaleX, + kASkewY, + kASkewX, + kAScaleY, + kATransX, + kATransY + }; + SkScalar operator[](int index) const { SkASSERT((unsigned)index < 9); return fMat[index]; @@ -108,8 +124,8 @@ public: SkScalar getSkewX() const { return fMat[kMSkewX]; } SkScalar getTranslateX() const { return fMat[kMTransX]; } SkScalar getTranslateY() const { return fMat[kMTransY]; } - SkScalar getPerspX() const { return fMat[kMPersp0]; } - SkScalar getPerspY() const { return fMat[kMPersp1]; } + SkPersp getPerspX() const { return fMat[kMPersp0]; } + SkPersp getPerspY() const { return fMat[kMPersp1]; } SkScalar& operator[](int index) { SkASSERT((unsigned)index < 9); @@ -129,12 +145,12 @@ public: void setSkewX(SkScalar v) { this->set(kMSkewX, v); } void setTranslateX(SkScalar v) { this->set(kMTransX, v); } void setTranslateY(SkScalar v) { this->set(kMTransY, v); } - void setPerspX(SkScalar v) { this->set(kMPersp0, v); } - void setPerspY(SkScalar v) { this->set(kMPersp1, v); } + void setPerspX(SkPersp v) { this->set(kMPersp0, v); } + void setPerspY(SkPersp v) { this->set(kMPersp1, v); } void setAll(SkScalar scaleX, SkScalar skewX, SkScalar transX, SkScalar skewY, SkScalar scaleY, SkScalar transY, - SkScalar persp0, SkScalar persp1, SkScalar persp2) { + SkPersp persp0, SkPersp persp1, SkPersp persp2) { fMat[kMScaleX] = scaleX; fMat[kMSkewX] = skewX; fMat[kMTransX] = transX; @@ -164,6 +180,10 @@ public: /** Set the matrix to scale by sx and sy. */ void setScale(SkScalar sx, SkScalar sy); + /** Set the matrix to scale by 1/divx and 1/divy. Returns false and doesn't + touch the matrix if either divx or divy is zero. + */ + bool setIDiv(int divx, int divy); /** Set the matrix to rotate by the specified number of degrees, with a pivot point at (px, py). The pivot point is the coordinate that should remain unchanged by the specified transformation. @@ -318,12 +338,19 @@ public: */ bool invert(SkMatrix* inverse) const; - /** Fills the passed array with the tranform values in the right order - for PDFs. If the matrix is a perspective transform, returns false - and fills the array with an identity transform. - @param transform The array to fill in. + /** Fills the passed array with affine identity values + in column major order. + @param affine The array to fill with affine identity values. + Must not be NULL. */ - bool pdfTransform(SkScalar transform[6]) const; + static void SetAffineIdentity(SkScalar affine[6]); + + /** Fills the passed array with the affine values in column major order. + If the matrix is a perspective transform, returns false + and does not change the passed array. + @param affine The array to fill with affine values. Ignored if NULL. + */ + bool asAffine(SkScalar affine[6]) const; /** Apply this matrix to the array of points specified by src, and write the transformed points into the array of points specified by dst. @@ -348,6 +375,31 @@ public: this->mapPoints(pts, pts, count); } + /** Like mapPoints but with custom byte stride between the points. Stride + * should be a multiple of sizeof(SkScalar). + */ + void mapPointsWithStride(SkPoint pts[], size_t stride, int count) const { + SkASSERT(stride >= sizeof(SkPoint)); + SkASSERT(0 == stride % sizeof(SkScalar)); + for (int i = 0; i < count; ++i) { + this->mapPoints(pts, pts, 1); + pts = (SkPoint*)((intptr_t)pts + stride); + } + } + + /** Like mapPoints but with custom byte stride between the points. + */ + void mapPointsWithStride(SkPoint dst[], SkPoint src[], + size_t stride, int count) const { + SkASSERT(stride >= sizeof(SkPoint)); + SkASSERT(0 == stride % sizeof(SkScalar)); + for (int i = 0; i < count; ++i) { + this->mapPoints(dst, src, 1); + src = (SkPoint*)((intptr_t)src + stride); + dst = (SkPoint*)((intptr_t)dst + stride); + } + } + void mapXY(SkScalar x, SkScalar y, SkPoint* result) const { SkASSERT(result); this->getMapXYProc()(*this, x, y, result); @@ -395,13 +447,6 @@ public: return this->mapRect(rect, *rect); } - void mapPointsWithStride(SkPoint pts[], size_t stride, int count) const { - for (int i = 0; i < count; ++i) { - this->mapPoints(pts, pts, 1); - pts = (SkPoint*)((intptr_t)pts + stride); - } - } - /** Return the mean radius of a circle after it has been mapped by this matrix. NOTE: in perspective this value assumes the circle has its center at the origin. @@ -466,10 +511,10 @@ public: void toDumpString(SkString*) const; /** - * Calculates the maximum stretching factor of the matrix. Only defined if - * the matrix does not have perspective. + * Calculates the maximum stretching factor of the matrix. If the matrix has + * perspective -1 is returned. * - * @return maximum strecthing factor or negative if matrix has perspective. + * @return maximum strecthing factor */ SkScalar getMaxStretch() const; @@ -484,6 +529,14 @@ public: */ static const SkMatrix& InvalidMatrix(); + /** + * Testing routine; the matrix's type cache should never need to be + * manually invalidated during normal use. + */ + void dirtyMatrixTypeCache() { + this->setTypeMask(kUnknown_Mask); + } + private: enum { /** Set if the matrix will map a rectangle to another rectangle. This @@ -494,6 +547,11 @@ private: */ kRectStaysRect_Mask = 0x10, + /** Set if the perspective bit is valid even though the rest of + the matrix is Unknown. + */ + kOnlyPerspectiveValid_Mask = 0x40, + kUnknown_Mask = 0x80, kORableMasks = kTranslate_Mask | @@ -512,10 +570,13 @@ private: mutable uint8_t fTypeMask; uint8_t computeTypeMask() const; + uint8_t computePerspectiveTypeMask() const; void setTypeMask(int mask) { // allow kUnknown or a valid mask - SkASSERT(kUnknown_Mask == mask || (mask & kAllMasks) == mask); + SkASSERT(kUnknown_Mask == mask || (mask & kAllMasks) == mask || + ((kUnknown_Mask | kOnlyPerspectiveValid_Mask | kPerspective_Mask) & mask) + == mask); fTypeMask = SkToU8(mask); } @@ -529,6 +590,24 @@ private: SkASSERT((mask & kAllMasks) == mask); fTypeMask &= ~mask; } + + TypeMask getPerspectiveTypeMaskOnly() const { + if ((fTypeMask & kUnknown_Mask) && + !(fTypeMask & kOnlyPerspectiveValid_Mask)) { + fTypeMask = this->computePerspectiveTypeMask(); + } + return (TypeMask)(fTypeMask & 0xF); + } + + /** Returns true if we already know that the matrix is identity; + false otherwise. + */ + bool isTriviallyIdentity() const { + if (fTypeMask & kUnknown_Mask) { + return false; + } + return ((fTypeMask & 0xF) == 0); + } static bool Poly2Proc(const SkPoint[], SkMatrix*, const SkPoint& scale); static bool Poly3Proc(const SkPoint[], SkMatrix*, const SkPoint& scale); @@ -560,4 +639,3 @@ private: }; #endif - diff --git a/include/core/SkMetaData.h b/include/core/SkMetaData.h index 1c34fd5..86f186f 100644 --- a/include/core/SkMetaData.h +++ b/include/core/SkMetaData.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMetaData_DEFINED #define SkMetaData_DEFINED diff --git a/include/core/SkOSFile.h b/include/core/SkOSFile.h index de8090c..9f01ead 100644 --- a/include/core/SkOSFile.h +++ b/include/core/SkOSFile.h @@ -1,26 +1,19 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + // #ifndef SkOSFile_DEFINED #define SkOSFile_DEFINED #include "SkString.h" -#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX) +#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_ANDROID) #include <dirent.h> #endif @@ -55,13 +48,17 @@ public: ~Iter(); void reset(const char path[], const char suffix[] = NULL); + /** If getDir is true, only returns directories. + Results are undefined if true and false calls are + interleaved on a single iterator. + */ bool next(SkString* name, bool getDir = false); private: #ifdef SK_BUILD_FOR_WIN HANDLE fHandle; uint16_t* fPath16; -#elif defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX) +#elif defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_ANDROID) DIR* fDIR; SkString fPath, fSuffix; #endif diff --git a/include/core/SkPackBits.h b/include/core/SkPackBits.h index c11231b..f0614a0 100644 --- a/include/core/SkPackBits.h +++ b/include/core/SkPackBits.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPackBits_DEFINED #define SkPackBits_DEFINED diff --git a/include/core/SkPaint.h b/include/core/SkPaint.h index 9b547a4..445f7eb 100644 --- a/include/core/SkPaint.h +++ b/include/core/SkPaint.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPaint_DEFINED #define SkPaint_DEFINED @@ -29,6 +22,7 @@ class SkFlattenableWriteBuffer; struct SkGlyph; struct SkRect; class SkGlyphCache; +class SkImageFilter; class SkMaskFilter; class SkMatrix; class SkPath; @@ -55,8 +49,8 @@ public: SkPaint& operator=(const SkPaint&); - SK_API friend int operator==(const SkPaint& a, const SkPaint& b); - friend int operator!=(const SkPaint& a, const SkPaint& b) { + SK_API friend bool operator==(const SkPaint& a, const SkPaint& b); + friend bool operator!=(const SkPaint& a, const SkPaint& b) { return !(a == b); } @@ -105,10 +99,12 @@ public: kLCDRenderText_Flag = 0x200, //!< mask to enable subpixel glyph renderering kEmbeddedBitmapText_Flag = 0x400, //!< mask to enable embedded bitmap strikes kAutoHinting_Flag = 0x800, //!< mask to force Freetype's autohinter + kVerticalText_Flag = 0x1000, + // when adding extra flags, note that the fFlags member is specified // with a bit-width and you'll have to expand it. - kAllFlags = 0xFFF + kAllFlags = 0x1FFF }; /** Return the paint's flags. Use the Flag enum to test flag values. @@ -165,21 +161,24 @@ public: return SkToBool(this->getFlags() & kSubpixelText_Flag); } - /** Helper for setFlags(), setting or clearing the kSubpixelText_Flag - bit @param subpixelText true to set the subpixelText bit in the paint's flags, - false to clear it. - */ + /** + * Helper for setFlags(), setting or clearing the kSubpixelText_Flag. + * @param subpixelText true to set the subpixelText bit in the paint's + * flags, false to clear it. + */ void setSubpixelText(bool subpixelText); bool isLCDRenderText() const { return SkToBool(this->getFlags() & kLCDRenderText_Flag); } - /** Helper for setFlags(), setting or clearing the kLCDRenderText_Flag bit - @param subpixelRender true to set the subpixelRenderText bit in the paint's flags, - false to clear it. - */ - void setLCDRenderText(bool subpixelRender); + /** + * Helper for setFlags(), setting or clearing the kLCDRenderText_Flag. + * Note: antialiasing must also be on for lcd rendering + * @param lcdText true to set the LCDRenderText bit in the paint's flags, + * false to clear it. + */ + void setLCDRenderText(bool lcdText); bool isEmbeddedBitmapText() const { return SkToBool(this->getFlags() & kEmbeddedBitmapText_Flag); @@ -202,6 +201,20 @@ public: */ void setAutohinted(bool useAutohinter); + bool isVerticalText() const { + return SkToBool(this->getFlags() & kVerticalText_Flag); + } + + /** + * Helper for setting or clearing the kVerticalText_Flag bit in + * setFlags(...). + * + * If this bit is set, then advances are treated as Y values rather than + * X values, and drawText will places its glyphs vertically rather than + * horizontally. + */ + void setVerticalText(bool); + /** Helper for getFlags(), returning true if kUnderlineText_Flag bit is set @return true if the underlineText bit is set in the paint's flags. */ @@ -600,6 +613,9 @@ public: */ SkRasterizer* setRasterizer(SkRasterizer* rasterizer); + SkImageFilter* getImageFilter() const { return fImageFilter; } + SkImageFilter* setImageFilter(SkImageFilter*); + /** * Return the paint's SkDrawLooper (if any). Does not affect the looper's * reference count. @@ -748,23 +764,29 @@ public: return this->textToGlyphs(text, byteLength, NULL); } - /** Return the width of the text. - @param text The text to be measured - @param length Number of bytes of text to measure - @param bounds If not NULL, returns the bounds of the text, - relative to (0, 0). - @param scale If not 0, return width as if the canvas were scaled - by this value - @return The advance width of the text - */ + /** Return the width of the text. This will return the vertical measure + * if isVerticalText() is true, in which case the returned value should + * be treated has a height instead of a width. + * + * @param text The text to be measured + * @param length Number of bytes of text to measure + * @param bounds If not NULL, returns the bounds of the text, + * relative to (0, 0). + * @param scale If not 0, return width as if the canvas were scaled + * by this value + * @return The advance width of the text + */ SkScalar measureText(const void* text, size_t length, SkRect* bounds, SkScalar scale = 0) const; - /** Return the width of the text. - @param text Address of the text - @param length Number of bytes of text to measure - @return The width of the text - */ + /** Return the width of the text. This will return the vertical measure + * if isVerticalText() is true, in which case the returned value should + * be treated has a height instead of a width. + * + * @param text Address of the text + * @param length Number of bytes of text to measure + * @return The width of the text + */ SkScalar measureText(const void* text, size_t length) const { return this->measureText(text, length, NULL, 0); } @@ -782,33 +804,38 @@ public: kBackward_TextBufferDirection }; - /** Return the width of the text. - @param text The text to be measured - @param length Number of bytes of text to measure - @param maxWidth Maximum width. Only the subset of text whose accumulated - widths are <= maxWidth are measured. - @param measuredWidth Optional. If non-null, this returns the actual - width of the measured text. - @param tbd Optional. The direction the text buffer should be - traversed during measuring. - @return The number of bytes of text that were measured. Will be - <= length. - */ + /** Return the number of bytes of text that were measured. If + * isVerticalText() is true, then the vertical advances are used for + * the measurement. + * + * @param text The text to be measured + * @param length Number of bytes of text to measure + * @param maxWidth Maximum width. Only the subset of text whose accumulated + * widths are <= maxWidth are measured. + * @param measuredWidth Optional. If non-null, this returns the actual + * width of the measured text. + * @param tbd Optional. The direction the text buffer should be + * traversed during measuring. + * @return The number of bytes of text that were measured. Will be + * <= length. + */ size_t breakText(const void* text, size_t length, SkScalar maxWidth, SkScalar* measuredWidth = NULL, TextBufferDirection tbd = kForward_TextBufferDirection) const; - /** Return the advance widths for the characters in the string. - @param text the text - @param byteLength number of bytes to of text - @param widths If not null, returns the array of advance widths of - the glyphs. If not NULL, must be at least a large - as the number of unichars in the specified text. - @param bounds If not null, returns the bounds for each of - character, relative to (0, 0) - @return the number of unichars in the specified text. - */ + /** Return the advances for the text. These will be vertical advances if + * isVerticalText() returns true. + * + * @param text the text + * @param byteLength number of bytes to of text + * @param widths If not null, returns the array of advances for + * the glyphs. If not NULL, must be at least a large + * as the number of unichars in the specified text. + * @param bounds If not null, returns the bounds for each of + * character, relative to (0, 0) + * @return the number of unichars in the specified text. + */ int getTextWidths(const void* text, size_t byteLength, SkScalar widths[], SkRect bounds[] = NULL) const; @@ -819,14 +846,22 @@ public: void getTextPath(const void* text, size_t length, SkScalar x, SkScalar y, SkPath* path) const; -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID const SkGlyph& getUnicharMetrics(SkUnichar); const SkGlyph& getGlyphMetrics(uint16_t); const void* findImage(const SkGlyph&); uint32_t getGenerationID() const; + + /** Returns the base glyph count for the strike associated with this paint + */ + unsigned getBaseGlyphCount(SkUnichar text) const; #endif + // returns true if the paint's settings (e.g. xfermode + alpha) resolve to + // mean that we need not draw at all (e.g. SrcOver + 0-alpha) + bool nothingToDraw() const; + private: SkTypeface* fTypeface; SkScalar fTextSize; @@ -840,20 +875,18 @@ private: SkColorFilter* fColorFilter; SkRasterizer* fRasterizer; SkDrawLooper* fLooper; + SkImageFilter* fImageFilter; SkColor fColor; SkScalar fWidth; SkScalar fMiterLimit; - unsigned fFlags : 12; + unsigned fFlags : 14; unsigned fTextAlign : 2; unsigned fCapType : 2; unsigned fJoinType : 2; unsigned fStyle : 2; unsigned fTextEncoding : 2; // 3 values unsigned fHinting : 2; -#ifdef ANDROID - uint32_t fGenerationID; -#endif SkDrawCacheProc getDrawCacheProc() const; SkMeasureCacheProc getMeasureCacheProc(TextBufferDirection dir, @@ -878,9 +911,15 @@ private: friend class SkDraw; friend class SkPDFDevice; friend class SkTextToPathIter; + +#ifdef SK_BUILD_FOR_ANDROID + // In order for the == operator to work properly this must be the last field + // in the struct so that we can do a memcmp to this field's offset. + uint32_t fGenerationID; +#endif }; -////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// #include "SkPathEffect.h" @@ -898,20 +937,18 @@ public: SkPaint::Cap, SkScalar miterLimit = -1); // overrides - // This method is not exported to java. virtual bool filterPath(SkPath* dst, const SkPath& src, SkScalar* width); // overrides for SkFlattenable - // This method is not exported to java. virtual void flatten(SkFlattenableWriteBuffer&); - // This method is not exported to java. virtual Factory getFactory(); + static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + private: SkScalar fWidth, fMiter; uint8_t fStyle, fJoin, fCap; - static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); SkStrokePathEffect(SkFlattenableReadBuffer&); typedef SkPathEffect INHERITED; diff --git a/include/core/SkPath.h b/include/core/SkPath.h index 7120d3f..859486c 100644 --- a/include/core/SkPath.h +++ b/include/core/SkPath.h @@ -1,26 +1,19 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPath_DEFINED #define SkPath_DEFINED #include "SkMatrix.h" #include "SkTDArray.h" -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID #define GEN_ID_INC fGenerationID++ #define GEN_ID_PTR_INC(ptr) ptr->fGenerationID++ #else @@ -45,7 +38,7 @@ public: ~SkPath(); SkPath& operator=(const SkPath&); - + friend bool operator==(const SkPath&, const SkPath&); friend bool operator!=(const SkPath& a, const SkPath& b) { return !(a == b); @@ -77,7 +70,7 @@ public: /** Set the path's fill type. This is used to define how "inside" is computed. The default value is kWinding_FillType. - + @param ft The new fill type for this path */ void setFillType(FillType ft) { @@ -187,6 +180,35 @@ public: */ bool isEmpty() const; + /** Test a line for zero length + + @return true if the line is of zero length; otherwise false. + */ + static bool IsLineDegenerate(const SkPoint& p1, const SkPoint& p2) { + return p1.equalsWithinTolerance(p2, SK_ScalarNearlyZero); + } + + /** Test a quad for zero length + + @return true if the quad is of zero length; otherwise false. + */ + static bool IsQuadDegenerate(const SkPoint& p1, const SkPoint& p2, + const SkPoint& p3) { + return p1.equalsWithinTolerance(p2, SK_ScalarNearlyZero) && + p2.equalsWithinTolerance(p3, SK_ScalarNearlyZero); + } + + /** Test a cubic curve for zero length + + @return true if the cubic is of zero length; otherwise false. + */ + static bool IsCubicDegenerate(const SkPoint& p1, const SkPoint& p2, + const SkPoint& p3, const SkPoint& p4) { + return p1.equalsWithinTolerance(p2, SK_ScalarNearlyZero) && + p2.equalsWithinTolerance(p3, SK_ScalarNearlyZero) && + p3.equalsWithinTolerance(p4, SK_ScalarNearlyZero); + } + /** Returns true if the path specifies a rectangle. If so, and if rect is not null, set rect to the bounds of the path. If the path does not specify a rectangle, return false and ignore rect. @@ -431,6 +453,24 @@ public: kCCW_Direction }; + /** + * Tries to quickly compute the direction of the first non-degenerate + * contour. If it can be computed, return true and set dir to that + * direction. If it cannot be (quickly) determined, return false and ignore + * the dir parameter. + */ + bool cheapComputeDirection(Direction* dir) const; + + /** + * Returns true if the path's direction can be computed via + * cheapComputDirection() and if that computed direction matches the + * specified direction. + */ + bool cheapIsDirection(Direction dir) const { + Direction computedDir; + return this->cheapComputeDirection(&computedDir) && computedDir == dir; + } + /** Add a closed rectangle contour to the path @param rect The rectangle to add as a closed contour to the path @param dir The direction to wind the rectangle's contour @@ -504,7 +544,7 @@ public: @param dx The amount to translate the path in X as it is added @param dx The amount to translate the path in Y as it is added */ - void addPath(const SkPath& src, SkScalar dx, SkScalar dy); + void addPath(const SkPath& src, SkScalar dx, SkScalar dy); /** Add a copy of src to the path */ @@ -519,6 +559,11 @@ public: */ void addPath(const SkPath& src, const SkMatrix& matrix); + /** + * Same as addPath(), but reverses the src input + */ + void reverseAddPath(const SkPath& src); + /** Offset the path by (dx,dy), returning true on success @param dx The amount in the X direction to offset the entire path @@ -553,11 +598,12 @@ public: } /** Return the last point on the path. If no points have been added, (0,0) - is returned. + is returned. If there are no points, this returns false, otherwise it + returns true. @param lastPt The last point on the path is returned here */ - void getLastPt(SkPoint* lastPt) const; + bool getLastPt(SkPoint* lastPt) const; /** Set the last point on the path. If no points have been added, moveTo(x,y) is automatically called. @@ -576,28 +622,47 @@ public: this->setLastPt(p.fX, p.fY); } + enum SegmentMask { + kLine_SegmentMask = 1 << 0, + kQuad_SegmentMask = 1 << 1, + kCubic_SegmentMask = 1 << 2 + }; + + /** + * Returns a mask, where each bit corresponding to a SegmentMask is + * set if the path contains 1 or more segments of that type. + * Returns 0 for an empty path (no segments). + */ + uint32_t getSegmentMasks() const { return fSegmentMask; } + enum Verb { kMove_Verb, //!< iter.next returns 1 point kLine_Verb, //!< iter.next returns 2 points kQuad_Verb, //!< iter.next returns 3 points kCubic_Verb, //!< iter.next returns 4 points - kClose_Verb, //!< iter.next returns 1 point (the last point) + kClose_Verb, //!< iter.next returns 1 point (contour's moveTo pt) kDone_Verb //!< iter.next returns 0 points }; /** Iterate through all of the segments (lines, quadratics, cubics) of each contours in a path. + + The iterator cleans up the segments along the way, removing degenerate + segments and adding close verbs where necessary. When the forceClose + argument is provided, each contour (as defined by a new starting + move command) will be completed with a close verb regardless of the + contour's contents. */ class SK_API Iter { public: - Iter(); - Iter(const SkPath&, bool forceClose); + Iter(); + Iter(const SkPath&, bool forceClose); void setPath(const SkPath&, bool forceClose); /** Return the next verb in this iteration of the path. When all segments have been visited, return kDone_Verb. - + @param pts The points representing the current verb and/or segment @return The verb for the current segment */ @@ -607,12 +672,12 @@ public: line was the result of a close() command (i.e. the end point is the initial moveto for this contour). If next() returned a different verb, this returns an undefined value. - + @return If the last call to next() returned kLine_Verb, return true if it was the result of an explicit close command. */ bool isCloseLine() const { return SkToBool(fCloseLine); } - + /** Returns true if the current contour is closed (has a kClose_Verb) @return true if the current contour is closed (has a kClose_Verb) */ @@ -626,11 +691,37 @@ public: SkPoint fLastPt; SkBool8 fForceClose; SkBool8 fNeedClose; - SkBool8 fNeedMoveTo; SkBool8 fCloseLine; + SkBool8 fSegmentState; bool cons_moveTo(SkPoint pts[1]); Verb autoClose(SkPoint pts[2]); + void consumeDegenerateSegments(); + }; + + /** Iterate through the verbs in the path, providing the associated points. + */ + class SK_API RawIter { + public: + RawIter(); + RawIter(const SkPath&); + + void setPath(const SkPath&); + + /** Return the next verb in this iteration of the path. When all + segments have been visited, return kDone_Verb. + + @param pts The points representing the current verb and/or segment + @return The verb for the current segment + */ + Verb next(SkPoint pts[4]); + + private: + const SkPoint* fPts; + const uint8_t* fVerbs; + const uint8_t* fVerbStop; + SkPoint fMoveTo; + SkPoint fLastPt; }; void dump(bool forceClose, const char title[] = NULL) const; @@ -639,13 +730,7 @@ public: void flatten(SkWriter32&) const; void unflatten(SkReader32&); - /** Subdivide the path so that no segment is longer that dist. - If bendLines is true, then turn all line segments into curves. - If dst == null, then the original path itself is modified (not const!) - */ - void subdivide(SkScalar dist, bool bendLines, SkPath* dst = NULL) const; - -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID uint32_t getGenerationID() const; #endif @@ -655,10 +740,11 @@ private: SkTDArray<SkPoint> fPts; SkTDArray<uint8_t> fVerbs; mutable SkRect fBounds; - mutable uint8_t fBoundsIsDirty; uint8_t fFillType; + uint8_t fSegmentMask; + mutable uint8_t fBoundsIsDirty; mutable uint8_t fConvexity; -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID uint32_t fGenerationID; #endif @@ -686,4 +772,3 @@ private: }; #endif - diff --git a/include/core/SkPathEffect.h b/include/core/SkPathEffect.h index eb1cc23..1b4cd5f 100644 --- a/include/core/SkPathEffect.h +++ b/include/core/SkPathEffect.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPathEffect_DEFINED #define SkPathEffect_DEFINED @@ -31,7 +24,6 @@ class SkPath; */ class SK_API SkPathEffect : public SkFlattenable { public: - // This method is not exported to java. SkPathEffect() {} /** Given a src path and a width value, return true if the patheffect @@ -42,6 +34,7 @@ public: */ virtual bool filterPath(SkPath* dst, const SkPath& src, SkScalar* width) = 0; + SK_DECLARE_FLATTENABLE_REGISTRAR() private: // illegal SkPathEffect(const SkPathEffect&); @@ -61,7 +54,7 @@ public: protected: SkPairPathEffect(SkFlattenableReadBuffer&); - virtual void flatten(SkFlattenableWriteBuffer&); + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; // these are visible to our subclasses SkPathEffect* fPE0, *fPE1; @@ -86,16 +79,16 @@ public: // overrides - // This method is not exported to java. virtual bool filterPath(SkPath* dst, const SkPath& src, SkScalar* width); -protected: - virtual Factory getFactory() { return CreateProc; } - -private: static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(SkComposePathEffect, (buffer)); } + +protected: + virtual Factory getFactory() SK_OVERRIDE { return CreateProc; } + +private: SkComposePathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {} // illegal @@ -121,16 +114,16 @@ public: : INHERITED(first, second) {} // overrides - // This method is not exported to java. virtual bool filterPath(SkPath* dst, const SkPath& src, SkScalar* width); -protected: - virtual Factory getFactory() { return CreateProc; } - -private: static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(SkSumPathEffect, (buffer)); } + +protected: + virtual Factory getFactory() SK_OVERRIDE { return CreateProc; } + +private: SkSumPathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {} // illegal diff --git a/include/core/SkPathMeasure.h b/include/core/SkPathMeasure.h index 2d94ae2..ec43834 100644 --- a/include/core/SkPathMeasure.h +++ b/include/core/SkPathMeasure.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPathMeasure_DEFINED #define SkPathMeasure_DEFINED diff --git a/include/core/SkPerspIter.h b/include/core/SkPerspIter.h index 81ce7c8..7f6add2 100644 --- a/include/core/SkPerspIter.h +++ b/include/core/SkPerspIter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPerspIter_DEFINED #define SkPerspIter_DEFINED diff --git a/include/core/SkPicture.h b/include/core/SkPicture.h index ac21bc9..47a2b95 100644 --- a/include/core/SkPicture.h +++ b/include/core/SkPicture.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2007 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPicture_DEFINED #define SkPicture_DEFINED diff --git a/include/core/SkPixelRef.h b/include/core/SkPixelRef.h index 8fb368a..e247479 100644 --- a/include/core/SkPixelRef.h +++ b/include/core/SkPixelRef.h @@ -1,26 +1,19 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2008 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPixelRef_DEFINED #define SkPixelRef_DEFINED +#include "SkBitmap.h" #include "SkRefCnt.h" #include "SkString.h" -class SkBitmap; class SkColorTable; struct SkIRect; class SkMutex; @@ -30,6 +23,25 @@ class SkFlattenableWriteBuffer; // this is an opaque class, not interpreted by skia class SkGpuTexture; +#if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS + +#define SK_DECLARE_PIXEL_REF_REGISTRAR() + +#define SK_DEFINE_PIXEL_REF_REGISTRAR(pixelRef) \ + static SkPixelRef::Registrar g##pixelRef##Reg(#pixelRef, \ + pixelRef::Create); + +#else + +#define SK_DECLARE_PIXEL_REF_REGISTRAR() static void Init(); + +#define SK_DEFINE_PIXEL_REF_REGISTRAR(pixelRef) \ + void pixelRef::Init() { \ + SkPixelRef::Registrar(#pixelRef, Create); \ + } + +#endif + /** \class SkPixelRef This class is the smart container for pixel memory, and is used with @@ -66,6 +78,14 @@ public: */ void unlockPixels(); + /** + * Some bitmaps can return a copy of their pixels for lockPixels(), but + * that copy, if modified, will not be pushed back. These bitmaps should + * not be used as targets for a raster device/canvas (since all pixels + * modifications will be lost when unlockPixels() is called.) + */ + bool lockPixelsAreWritable() const; + /** Returns a non-zero, unique value corresponding to the pixels in this pixelref. Each time the pixels are changed (and notifyPixelsChanged is called), a different generation ID will be returned. @@ -116,6 +136,12 @@ public: bool readPixels(SkBitmap* dst, const SkIRect* subset = NULL); + /** Makes a deep copy of this PixelRef, respecting the requested config. + Returns NULL if either there is an error (e.g. the destination could + not be created with the given config), or this PixelRef does not + support deep copies. */ + virtual SkPixelRef* deepCopy(SkBitmap::Config config) { return NULL; } + // serialization typedef SkPixelRef* (*Factory)(SkFlattenableReadBuffer&); @@ -123,7 +149,7 @@ public: virtual Factory getFactory() const { return NULL; } virtual void flatten(SkFlattenableWriteBuffer&) const; -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID /** * Acquire a "global" ref on this object. * The default implementation just calls ref(), but subclasses can override @@ -161,6 +187,9 @@ protected: */ virtual void onUnlockPixels() = 0; + /** Default impl returns true */ + virtual bool onLockPixelsAreWritable() const; + /** * For pixelrefs that don't have access to their raw pixels, they may be * able to make a copy of them (e.g. if the pixels are on the GPU). @@ -177,6 +206,10 @@ protected: SkPixelRef(SkFlattenableReadBuffer&, SkMutex*); private: +#if !SK_ALLOW_STATIC_GLOBAL_INITIALIZERS + static void InitializeFlattenables(); +#endif + SkMutex* fMutex; // must remain in scope for the life of this object void* fPixels; SkColorTable* fColorTable; // we do not track ownership, subclass does @@ -188,6 +221,8 @@ private: // can go from false to true, but never from true to false bool fIsImmutable; + + friend class SkGraphics; }; #endif diff --git a/include/core/SkPoint.h b/include/core/SkPoint.h index d74435e..de7c0ef 100644 --- a/include/core/SkPoint.h +++ b/include/core/SkPoint.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPoint_DEFINED #define SkPoint_DEFINED @@ -196,6 +189,16 @@ struct SK_API SkPoint { } void setRectFan(SkScalar l, SkScalar t, SkScalar r, SkScalar b, size_t stride); + static void Offset(SkPoint points[], int count, const SkPoint& offset) { + Offset(points, count, offset.fX, offset.fY); + } + + static void Offset(SkPoint points[], int count, SkScalar dx, SkScalar dy) { + for (int i = 0; i < count; ++i) { + points[i].offset(dx, dy); + } + } + void offset(SkScalar dx, SkScalar dy) { fX += dx; fY += dy; @@ -206,10 +209,19 @@ struct SK_API SkPoint { SkScalar length() const { return SkPoint::Length(fX, fY); } SkScalar distanceToOrigin() const { return this->length(); } + /** + * Return true if the computed length of the vector is >= the internal + * tolerance (used to avoid dividing by tiny values). + */ + static bool CanNormalize(SkScalar dx, SkScalar dy); + + bool canNormalize() const { + return CanNormalize(fX, fY); + } + /** Set the point (vector) to be unit-length in the same direction as it - currently is, and return its old length. If the old length is - degenerately small (nearly zero), do nothing and return false, otherwise - return true. + already points. If the point has a degenerate length (i.e. nearly 0) + then return false and do nothing; otherwise return true. */ bool normalize(); @@ -303,6 +315,13 @@ struct SK_API SkPoint { return a.fX != b.fX || a.fY != b.fY; } + /** Return true if this and the given point are componentwise within tol. + */ + bool equalsWithinTolerance(const SkPoint& v, SkScalar tol) const { + return SkScalarNearlyZero(fX - v.fX, tol) + && SkScalarNearlyZero(fY - v.fY, tol); + } + /** Returns a new point whose coordinates are the difference between a's and b's (a - b) */ @@ -325,7 +344,13 @@ struct SK_API SkPoint { static SkScalar Length(SkScalar x, SkScalar y); /** Normalize pt, returning its previous length. If the prev length is too - small (degenerate), return 0 and leave pt unchanged. + small (degenerate), return 0 and leave pt unchanged. This uses the same + tolerance as CanNormalize. + + Note that this method may be significantly more expensive than + the non-static normalize(), because it has to return the previous length + of the point. If you don't need the previous length, call the + non-static normalize() method instead. */ static SkScalar Normalize(SkPoint* pt); @@ -364,17 +389,70 @@ struct SK_API SkPoint { SkScalar dy = fY - pt.fY; return SkScalarMul(dx, dx) + SkScalarMul(dy, dy); } - - SkScalar distanceToLineSegmentBetweenSqd(const SkPoint& a, + + /** + * The side of a point relative to a line. If the line is from a to b then + * the values are consistent with the sign of (b-a) cross (pt-a) + */ + enum Side { + kLeft_Side = -1, + kOn_Side = 0, + kRight_Side = 1 + }; + + /** + * Returns the squared distance to the infinite line between two pts. Also + * optionally returns the side of the line that the pt falls on (looking + * along line from a to b) + */ + SkScalar distanceToLineBetweenSqd(const SkPoint& a, + const SkPoint& b, + Side* side = NULL) const; + + /** + * Returns the distance to the infinite line between two pts. Also + * optionally returns the side of the line that the pt falls on (looking + * along the line from a to b) + */ + SkScalar distanceToLineBetween(const SkPoint& a, + const SkPoint& b, + Side* side = NULL) const { + return SkScalarSqrt(this->distanceToLineBetweenSqd(a, b, side)); + } + + /** + * Returns the squared distance to the line segment between pts a and b + */ + SkScalar distanceToLineSegmentBetweenSqd(const SkPoint& a, const SkPoint& b) const; - - SkScalar distanceToLineSegmentBetween(const SkPoint& a, + + /** + * Returns the distance to the line segment between pts a and b. + */ + SkScalar distanceToLineSegmentBetween(const SkPoint& a, const SkPoint& b) const { return SkScalarSqrt(this->distanceToLineSegmentBetweenSqd(a, b)); } + + /** + * Make this vector be orthogonal to vec. Looking down vec the + * new vector will point in direction indicated by side (which + * must be kLeft_Side or kRight_Side). + */ + void setOrthog(const SkPoint& vec, Side side = kLeft_Side) { + // vec could be this + SkScalar tmp = vec.fX; + if (kLeft_Side == side) { + fX = -vec.fY; + fY = tmp; + } else { + SkASSERT(kRight_Side == side); + fX = vec.fY; + fY = -tmp; + } + } }; typedef SkPoint SkVector; #endif - diff --git a/include/core/SkPostConfig.h b/include/core/SkPostConfig.h index 23ce02b..edce334 100644 --- a/include/core/SkPostConfig.h +++ b/include/core/SkPostConfig.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPostConfig_DEFINED #define SkPostConfig_DEFINED @@ -63,6 +56,32 @@ #endif #endif +#if !defined(SK_HAS_COMPILER_FEATURE) + #if defined(__has_feature) + #define SK_HAS_COMPILER_FEATURE(x) __has_feature(x) + #else + #define SK_HAS_COMPILER_FEATURE(x) 0 + #endif +#endif + +/** + * The clang static analyzer likes to know that when the program is not + * expected to continue (crash, assertion failure, etc). It will notice that + * some combination of parameters lead to a function call that does not return. + * It can then make appropriate assumptions about the parameters in code + * executed only if the non-returning function was *not* called. + */ +#if !defined(SkNO_RETURN_HINT) + #if SK_HAS_COMPILER_FEATURE(attribute_analyzer_noreturn) + namespace { + inline void SkNO_RETURN_HINT() __attribute__((analyzer_noreturn)); + void SkNO_RETURN_HINT() {} + } + #else + #define SkNO_RETURN_HINT() do {} while (false) + #endif +#endif + /////////////////////////////////////////////////////////////////////////////// #ifndef SkNEW @@ -75,9 +94,9 @@ #ifndef SK_CRASH #if 1 // set to 0 for infinite loop, which can help connecting gdb - #define SK_CRASH() *(int *)(uintptr_t)0xbbadbeef = 0 + #define SK_CRASH() do { SkNO_RETURN_HINT(); *(int *)(uintptr_t)0xbbadbeef = 0; } while (false) #else - #define SK_CRASH() do {} while (true) + #define SK_CRASH() do { SkNO_RETURN_HINT(); } while (true) #endif #endif @@ -107,7 +126,7 @@ #endif #ifndef SK_DEBUGBREAK - #define SK_DEBUGBREAK(cond) do { if (!(cond)) __debugbreak(); } while (false) + #define SK_DEBUGBREAK(cond) do { if (!(cond)) { SkNO_RETURN_HINT(); __debugbreak(); }} while (false) #endif #ifndef SK_A32_SHIFT @@ -252,7 +271,28 @@ #define DEBUG_CLIENTBLOCK #endif // _DEBUG + #endif #endif +////////////////////////////////////////////////////////////////////// + +#ifndef SK_OVERRIDE +#if defined(_MSC_VER) +#define SK_OVERRIDE override +#elif defined(__clang__) +// Some documentation suggests we should be using __attribute__((override)), +// but it doesn't work. +#define SK_OVERRIDE override +#else +// Linux GCC ignores "__attribute__((override))" and rejects "override". +#define SK_OVERRIDE +#endif +#endif + +////////////////////////////////////////////////////////////////////// + +#ifndef SK_ALLOW_STATIC_GLOBAL_INITIALIZERS +#define SK_ALLOW_STATIC_GLOBAL_INITIALIZERS 1 +#endif diff --git a/include/core/SkPreConfig.h b/include/core/SkPreConfig.h index 6ec73ce..4485f1d 100644 --- a/include/core/SkPreConfig.h +++ b/include/core/SkPreConfig.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPreConfig_DEFINED #define SkPreConfig_DEFINED @@ -23,7 +16,7 @@ ////////////////////////////////////////////////////////////////////// -#if !defined(SK_BUILD_FOR_ANDROID_NDK) && !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_PALM) && !defined(SK_BUILD_FOR_WINCE) && !defined(SK_BUILD_FOR_WIN32) && !defined(SK_BUILD_FOR_SYMBIAN) && !defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_MAC) && !defined(SK_BUILD_FOR_SDL) && !defined(SK_BUILD_FOR_BREW) +#if !defined(SK_BUILD_FOR_ANDROID) && !defined(SK_BUILD_FOR_ANDROID_NDK) && !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_PALM) && !defined(SK_BUILD_FOR_WINCE) && !defined(SK_BUILD_FOR_WIN32) && !defined(SK_BUILD_FOR_SYMBIAN) && !defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_MAC) && !defined(SK_BUILD_FOR_SDL) && !defined(SK_BUILD_FOR_BREW) #ifdef __APPLE__ #include "TargetConditionals.h" @@ -37,7 +30,12 @@ #define SK_BUILD_FOR_WIN32 #elif defined(__SYMBIAN32__) #define SK_BUILD_FOR_WIN32 - #elif defined(linux) + #elif defined(ANDROID_NDK) + #define SK_BUILD_FOR_ANDROID_NDK + #elif defined(ANDROID) + #define SK_BUILD_FOR_ANDROID + #elif defined(linux) || defined(__FreeBSD__) || defined(__OpenBSD__) || \ + defined(__sun) || defined(__NetBSD__) || defined(__DragonFly__) #define SK_BUILD_FOR_UNIX #elif TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR #define SK_BUILD_FOR_IOS @@ -45,12 +43,15 @@ #define SK_BUILD_FOR_MAC #endif - #if defined(ANDROID) - #define SK_BUILD_FOR_ANDROID - #endif - #if defined(ANDROID_NDK) - #define SK_BUILD_FOR_ANDROID_NDK - #endif +#endif + +/* Even if the user only defined the NDK variant we still need to build + * the default Android code. Therefore, when attempting to include/exclude + * something from the NDK variant check first that we are building for + * Android then check the status of the NDK define. + */ +#if defined(SK_BUILD_FOR_ANDROID_NDK) && !defined(SK_BUILD_FOR_ANDROID) + #define SK_BUILD_FOR_ANDROID #endif ////////////////////////////////////////////////////////////////////// @@ -64,7 +65,9 @@ #endif #ifdef SK_BUILD_FOR_WIN32 - #define SK_RESTRICT + #if !defined(SK_RESTRICT) + #define SK_RESTRICT __restrict + #endif #include "sk_stdint.h" #endif diff --git a/include/core/SkPtrRecorder.h b/include/core/SkPtrRecorder.h index db6c64d..11fd170 100644 --- a/include/core/SkPtrRecorder.h +++ b/include/core/SkPtrRecorder.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPtrSet_DEFINED #define SkPtrSet_DEFINED @@ -89,10 +82,13 @@ private: */ template <typename T> class SkTPtrSet : public SkPtrSet { public: + uint32_t find(T ptr) { + return this->INHERITED::find((void*)ptr); + } uint32_t add(T ptr) { return this->INHERITED::add((void*)ptr); } - + void copyToArray(T* array) const { this->INHERITED::copyToArray((void**)array); } diff --git a/include/core/SkRandom.h b/include/core/SkRandom.h index 33b563a..b850df3 100644 --- a/include/core/SkRandom.h +++ b/include/core/SkRandom.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkRandom_DEFINED #define SkRandom_DEFINED diff --git a/include/core/SkRasterizer.h b/include/core/SkRasterizer.h index d81e613..d249898 100644 --- a/include/core/SkRasterizer.h +++ b/include/core/SkRasterizer.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkRasterizer_DEFINED #define SkRasterizer_DEFINED @@ -35,7 +28,7 @@ public: const SkIRect* clipBounds, SkMaskFilter* filter, SkMask* mask, SkMask::CreateMode mode); - virtual void flatten(SkFlattenableWriteBuffer& ) {} + virtual void flatten(SkFlattenableWriteBuffer& ) SK_OVERRIDE {} protected: SkRasterizer(SkFlattenableReadBuffer&); diff --git a/include/core/SkReader32.h b/include/core/SkReader32.h index 654ebd5..37ace5c 100644 --- a/include/core/SkReader32.h +++ b/include/core/SkReader32.h @@ -1,27 +1,18 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkReader32_DEFINED #define SkReader32_DEFINED -#include "SkTypes.h" - #include "SkScalar.h" -#include "SkPoint.h" -#include "SkRect.h" + +class SkString; class SkReader32 : SkNoncopyable { public: @@ -73,14 +64,6 @@ public: return value; } - const SkPoint* skipPoint() { - return (const SkPoint*)this->skip(sizeof(SkPoint)); - } - - const SkRect* skipRect() { - return (const SkRect*)this->skip(sizeof(SkRect)); - } - const void* skip(size_t size) { SkASSERT(ptr_align_4(fCurr)); const void* addr = fCurr; @@ -89,6 +72,11 @@ public: return addr; } + template <typename T> const T& skipT() { + SkASSERT(SkAlign4(sizeof(T)) == sizeof(T)); + return *(const T*)this->skip(sizeof(T)); + } + void read(void* dst, size_t size) { SkASSERT(0 == size || dst != NULL); SkASSERT(ptr_align_4(fCurr)); @@ -103,12 +91,18 @@ public: uint32_t readU32() { return this->readInt(); } /** - * Read the length of a string written by SkWriter32::writeString() - * (if len is not NULL) and return the null-ternimated address of the - * string. + * Read the length of a string (written by SkWriter32::writeString) into + * len (if len is not NULL) and return the null-ternimated address of the + * string within the reader's buffer. */ const char* readString(size_t* len = NULL); + /** + * Read the string (written by SkWriter32::writeString) and return it in + * copy (if copy is not null). Return the length of the string. + */ + size_t readIntoString(SkString* copy); + private: // these are always 4-byte aligned const char* fCurr; // current position within buffer @@ -116,8 +110,7 @@ private: const char* fBase; // beginning of buffer #ifdef SK_DEBUG - static bool ptr_align_4(const void* ptr) - { + static bool ptr_align_4(const void* ptr) { return (((const char*)ptr - (const char*)NULL) & 3) == 0; } #endif diff --git a/include/core/SkRect.h b/include/core/SkRect.h index 19ee12a..65e7611 100644 --- a/include/core/SkRect.h +++ b/include/core/SkRect.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkRect_DEFINED #define SkRect_DEFINED @@ -56,27 +49,39 @@ struct SK_API SkIRect { r.set(x, y, x + w, y + h); return r; } - - /** Return true if the rectangle's width or height are <= 0 - */ - bool isEmpty() const { return fLeft >= fRight || fTop >= fBottom; } - /** Returns the rectangle's width. This does not check for a valid rectangle (i.e. left <= right) - so the result may be negative. - */ + int left() const { return fLeft; } + int top() const { return fTop; } + int right() const { return fRight; } + int bottom() const { return fBottom; } + + /** return the left edge of the rect */ + int x() const { return fLeft; } + /** return the top edge of the rect */ + int y() const { return fTop; } + /** + * Returns the rectangle's width. This does not check for a valid rect + * (i.e. left <= right) so the result may be negative. + */ int width() const { return fRight - fLeft; } - - /** Returns the rectangle's height. This does not check for a valid rectangle (i.e. top <= bottom) - so the result may be negative. - */ + + /** + * Returns the rectangle's height. This does not check for a valid rect + * (i.e. top <= bottom) so the result may be negative. + */ int height() const { return fBottom - fTop; } + + /** + * Return true if the rectangle's width or height are <= 0 + */ + bool isEmpty() const { return fLeft >= fRight || fTop >= fBottom; } - friend int operator==(const SkIRect& a, const SkIRect& b) { + friend bool operator==(const SkIRect& a, const SkIRect& b) { return !memcmp(&a, &b, sizeof(a)); } - friend int operator!=(const SkIRect& a, const SkIRect& b) { - return memcmp(&a, &b, sizeof(a)); + friend bool operator!=(const SkIRect& a, const SkIRect& b) { + return !(a == b); } bool is16Bit() const { @@ -330,10 +335,34 @@ struct SK_API SkRect { return r; } - /** Return true if the rectangle's width or height are <= 0 - */ - bool isEmpty() const { return fLeft >= fRight || fTop >= fBottom; } - bool hasValidCoordinates() const; + /** + * Return true if the rectangle's width or height are <= 0 + */ + bool isEmpty() const { return fLeft >= fRight || fTop >= fBottom; } + + /** + * Returns true iff all values in the rect are finite. If any are + * infinite or NaN (or SK_FixedNaN when SkScalar is fixed) then this + * returns false. + */ + bool isFinite() const { +#ifdef SK_SCALAR_IS_FLOAT + // x * 0 will be NaN iff x is infinity or NaN. + // a + b will be NaN iff either a or b is NaN. + float value = fLeft * 0 + fTop * 0 + fRight * 0 + fBottom * 0; + + // value is either NaN or it is finite (zero). + // value==value will be true iff value is not NaN + return value == value; +#else + // use bit-or for speed, since we don't care about short-circuting the + // tests, and we expect the common case will be that we need to check all. + int isNaN = (SK_FixedNaN == fLeft) | (SK_FixedNaN == fTop) | + (SK_FixedNaN == fRight) | (SK_FixedNaN == fBottom); + return !isNaN; +#endif + } + SkScalar left() const { return fLeft; } SkScalar top() const { return fTop; } SkScalar right() const { return fRight; } @@ -343,12 +372,12 @@ struct SK_API SkRect { SkScalar centerX() const { return SkScalarHalf(fLeft + fRight); } SkScalar centerY() const { return SkScalarHalf(fTop + fBottom); } - friend int operator==(const SkRect& a, const SkRect& b) { - return !memcmp(&a, &b, sizeof(a)); + friend bool operator==(const SkRect& a, const SkRect& b) { + return 0 == memcmp(&a, &b, sizeof(a)); } - friend int operator!=(const SkRect& a, const SkRect& b) { - return memcmp(&a, &b, sizeof(a)); + friend bool operator!=(const SkRect& a, const SkRect& b) { + return 0 != memcmp(&a, &b, sizeof(a)); } /** return the 4 points that enclose the rectangle @@ -436,9 +465,10 @@ struct SK_API SkRect { this->offset(delta.fX, delta.fY); } - /** Inset the rectangle by (dx,dy). If dx is positive, then the sides are moved inwards, - making the rectangle narrower. If dx is negative, then the sides are moved outwards, - making the rectangle wider. The same hods true for dy and the top and bottom. + /** Inset the rectangle by (dx,dy). If dx is positive, then the sides are + moved inwards, making the rectangle narrower. If dx is negative, then + the sides are moved outwards, making the rectangle wider. The same holds + true for dy and the top and bottom. */ void inset(SkScalar dx, SkScalar dy) { fLeft += dx; @@ -447,6 +477,13 @@ struct SK_API SkRect { fBottom -= dy; } + /** Outset the rectangle by (dx,dy). If dx is positive, then the sides are + moved outwards, making the rectangle wider. If dx is negative, then the + sides are moved inwards, making the rectangle narrower. The same hods + true for dy and the top and bottom. + */ + void outset(SkScalar dx, SkScalar dy) { this->inset(-dx, -dy); } + /** If this rectangle intersects r, return true and set this rectangle to that intersection, otherwise return false and do not change this rectangle. If either rectangle is empty, do nothing and return false. @@ -472,6 +509,12 @@ struct SK_API SkRect { fLeft < right && left < fRight && fTop < bottom && top < fBottom; } + + /** If rectangles a and b intersect, return true and set this rectangle to + * that intersection, otherwise return false and do not change this + * rectangle. If either rectangle is empty, do nothing and return false. + */ + bool intersect(const SkRect& a, const SkRect& b); /** * Return true if rectangles a and b are not empty and intersect. @@ -574,6 +617,18 @@ struct SK_API SkRect { } /** + * Expand this rectangle by rounding its coordinates "out", choosing the + * floor of top and left, and the ceil of right and bottom. If this rect + * is already on integer coordinates, then it will be unchanged. + */ + void roundOut() { + this->set(SkScalarFloorToScalar(fLeft), + SkScalarFloorToScalar(fTop), + SkScalarCeilToScalar(fRight), + SkScalarCeilToScalar(fBottom)); + } + + /** * Swap top/bottom or left/right if there are flipped (i.e. if width() * or height() would have returned a negative value.) This should be called * if the edges are computed separately, and may have crossed over each diff --git a/include/core/SkRefCnt.h b/include/core/SkRefCnt.h index 36f4249..7af0017 100644 --- a/include/core/SkRefCnt.h +++ b/include/core/SkRefCnt.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkRefCnt_DEFINED #define SkRefCnt_DEFINED @@ -37,7 +30,12 @@ public: /** Destruct, asserting that the reference count is 1. */ - virtual ~SkRefCnt() { SkASSERT(fRefCnt == 1); } + virtual ~SkRefCnt() { +#ifdef SK_DEBUG + SkASSERT(fRefCnt == 1); + fRefCnt = 0; // illegal value, to catch us if we reuse after delete +#endif + } /** Return the reference count. */ @@ -63,20 +61,61 @@ public: } } + void validate() const { + SkASSERT(fRefCnt > 0); + } + private: mutable int32_t fRefCnt; }; +/////////////////////////////////////////////////////////////////////////////// + +/** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for + null in on each side of the assignment, and ensuring that ref() is called + before unref(), in case the two pointers point to the same object. + */ +#define SkRefCnt_SafeAssign(dst, src) \ + do { \ + if (src) src->ref(); \ + if (dst) dst->unref(); \ + dst = src; \ + } while (0) + + +/** Check if the argument is non-null, and if so, call obj->ref() + */ +template <typename T> static inline void SkSafeRef(T* obj) { + if (obj) { + obj->ref(); + } +} + +/** Check if the argument is non-null, and if so, call obj->unref() + */ +template <typename T> static inline void SkSafeUnref(T* obj) { + if (obj) { + obj->unref(); + } +} + +/////////////////////////////////////////////////////////////////////////////// + /** * Utility class that simply unref's its argument in the destructor. */ template <typename T> class SkAutoTUnref : SkNoncopyable { public: - SkAutoTUnref(T* obj) : fObj(obj) {} + explicit SkAutoTUnref(T* obj = NULL) : fObj(obj) {} ~SkAutoTUnref() { SkSafeUnref(fObj); } T* get() const { return fObj; } + void reset(T* obj) { + SkSafeUnref(fObj); + fObj = obj; + } + /** * Return the hosted object (which may be null), transferring ownership. * The reference count is not modified, and the internal ptr is set to NULL @@ -98,35 +137,13 @@ public: SkAutoUnref(SkRefCnt* obj) : SkAutoTUnref<SkRefCnt>(obj) {} }; -/////////////////////////////////////////////////////////////////////////////// - -/** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for - null in on each side of the assignment, and ensuring that ref() is called - before unref(), in case the two pointers point to the same object. -*/ -#define SkRefCnt_SafeAssign(dst, src) \ - do { \ - if (src) src->ref(); \ - if (dst) dst->unref(); \ - dst = src; \ - } while (0) - - -/** Check if the argument is non-null, and if so, call obj->ref() - */ -template <typename T> static inline void SkSafeRef(T* obj) { - if (obj) { - obj->ref(); - } -} - -/** Check if the argument is non-null, and if so, call obj->unref() - */ -template <typename T> static inline void SkSafeUnref(T* obj) { - if (obj) { - obj->unref(); - } -} +class SkAutoRef : SkNoncopyable { +public: + SkAutoRef(SkRefCnt* obj) : fObj(obj) { SkSafeRef(obj); } + ~SkAutoRef() { SkSafeUnref(fObj); } +private: + SkRefCnt* fObj; +}; /** Wrapper class for SkRefCnt pointers. This manages ref/unref of a pointer to a SkRefCnt (or subclass) object. diff --git a/include/core/SkRefDict.h b/include/core/SkRefDict.h index 0c4b025..6751121 100644 --- a/include/core/SkRefDict.h +++ b/include/core/SkRefDict.h @@ -1,19 +1,12 @@ -/* - Copyright 2011 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkRefDict_DEFINED #define SkRefDict_DEFINED diff --git a/include/core/SkRegion.h b/include/core/SkRegion.h index 1dace59..9d89d94 100644 --- a/include/core/SkRegion.h +++ b/include/core/SkRegion.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2005 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2005 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkRegion_DEFINED #define SkRegion_DEFINED @@ -93,9 +86,9 @@ public: const SkIRect& getBounds() const { return fBounds; } /** - * Returns true if the region is non-empty, and if so, sets the specified - * path to the boundary(s) of the region. If the region is empty, then - * this returns false, and path is left unmodified. + * Returns true if the region is non-empty, and if so, appends the + * boundary(s) of the region to the specified path. + * If the region is empty, returns false, and path is left unmodified. */ bool getBoundaryPath(SkPath* path) const; @@ -290,7 +283,7 @@ public: */ bool op(const SkRegion& rgna, const SkRegion& rgnb, Op op); -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID /** Returns a new char* containing the list of rectangles in this region */ char* toString(); diff --git a/include/core/SkRelay.h b/include/core/SkRelay.h index 9361482..ef09ce4 100644 --- a/include/core/SkRelay.h +++ b/include/core/SkRelay.h @@ -1,19 +1,12 @@ -/* - Copyright 2010 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTRelay_DEFINED #define SkTRelay_DEFINED diff --git a/include/core/SkScalar.h b/include/core/SkScalar.h index ba113f4..71aad98 100644 --- a/include/core/SkScalar.h +++ b/include/core/SkScalar.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkScalar_DEFINED #define SkScalar_DEFINED @@ -99,7 +92,7 @@ * * Either way, it's not good. */ - SkASSERT(!"looks like you passed an SkScalar into SkIntToScalar"); + SkDEBUGFAIL("looks like you passed an SkScalar into SkIntToScalar"); return (float)0; } #else // not SK_DEBUG @@ -123,15 +116,15 @@ /** SkScalarFraction(x) returns the signed fractional part of the argument */ #define SkScalarFraction(x) sk_float_mod(x, 1.0f) - /** Rounds the SkScalar to the nearest integer value - */ - #define SkScalarRound(x) sk_float_round2int(x) - /** Returns the smallest integer that is >= the specified SkScalar - */ - #define SkScalarCeil(x) sk_float_ceil2int(x) - /** Returns the largest integer that is <= the specified SkScalar - */ - #define SkScalarFloor(x) sk_float_floor2int(x) + + #define SkScalarFloorToScalar(x) sk_float_floor(x) + #define SkScalarCeilToScalar(x) sk_float_ceil(x) + #define SkScalarRoundToScalar(x) sk_float_floor((x) + 0.5f) + + #define SkScalarFloorToInt(x) sk_float_floor2int(x) + #define SkScalarCeilToInt(x) sk_float_ceil2int(x) + #define SkScalarRoundToInt(x) sk_float_round2int(x) + /** Returns the absolute value of the specified SkScalar */ #define SkScalarAbs(x) sk_float_abs(x) @@ -237,9 +230,15 @@ #define SkDoubleToScalar(n) SkDoubleToFixed(n) #endif #define SkScalarFraction(x) SkFixedFraction(x) - #define SkScalarRound(x) SkFixedRound(x) - #define SkScalarCeil(x) SkFixedCeil(x) - #define SkScalarFloor(x) SkFixedFloor(x) + + #define SkScalarFloorToScalar(x) SkFixedFloorToFixed(x) + #define SkScalarCeilToScalar(x) SkFixedCeilToFixed(x) + #define SkScalarRoundToScalar(x) SkFixedRoundToFixed(x) + + #define SkScalarFloorToInt(x) SkFixedFloorToInt(x) + #define SkScalarCeilToInt(x) SkFixedCeilToInt(x) + #define SkScalarRoundToInt(x) SkFixedRoundToInt(x) + #define SkScalarAbs(x) SkFixedAbs(x) #define SkScalarCopySign(x, y) SkCopySign32(x, y) #define SkScalarClampMax(x, max) SkClampMax(x, max) @@ -284,17 +283,43 @@ } #endif +// DEPRECATED : use ToInt or ToScalar variant +#define SkScalarFloor(x) SkScalarFloorToInt(x) +#define SkScalarCeil(x) SkScalarCeilToInt(x) +#define SkScalarRound(x) SkScalarRoundToInt(x) + +/** + * Returns -1 || 0 || 1 depending on the sign of value: + * -1 if x < 0 + * 0 if x == 0 + * 1 if x > 0 + */ +static inline int SkScalarSignAsInt(SkScalar x) { + return x < 0 ? -1 : (x > 0); +} + +// Scalar result version of above +static inline SkScalar SkScalarSignAsScalar(SkScalar x) { + return x < 0 ? -SK_Scalar1 : ((x > 0) ? SK_Scalar1 : 0); +} + #define SK_ScalarNearlyZero (SK_Scalar1 / (1 << 12)) /* <= is slower than < for floats, so we use < for our tolerance test */ static inline bool SkScalarNearlyZero(SkScalar x, - SkScalar tolerance = SK_ScalarNearlyZero) { + SkScalar tolerance = SK_ScalarNearlyZero) { SkASSERT(tolerance > 0); return SkScalarAbs(x) < tolerance; } +static inline bool SkScalarNearlyEqual(SkScalar x, SkScalar y, + SkScalar tolerance = SK_ScalarNearlyZero) { + SkASSERT(tolerance > 0); + return SkScalarAbs(x-y) < tolerance; +} + /** Linearly interpolate between A and B, based on t. If t is 0, return A If t is 1, return B diff --git a/include/core/SkScalarCompare.h b/include/core/SkScalarCompare.h index 7f0b176..0842fdd 100644 --- a/include/core/SkScalarCompare.h +++ b/include/core/SkScalarCompare.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkScalarCompare_DEFINED #define SkScalarCompare_DEFINED diff --git a/include/core/SkScalerContext.h b/include/core/SkScalerContext.h index cbbbdf0..e7dd7d4 100644 --- a/include/core/SkScalerContext.h +++ b/include/core/SkScalerContext.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkScalerContext_DEFINED #define SkScalerContext_DEFINED @@ -60,7 +53,9 @@ struct SkGlyph { unsigned rb = width; if (SkMask::kBW_Format == format) { rb = (rb + 7) >> 3; - } else if (SkMask::kARGB32_Format == format) { + } else if (SkMask::kARGB32_Format == format || + SkMask::kLCD32_Format == format) + { rb <<= 2; } else if (SkMask::kLCD16_Format == format) { rb = SkAlign4(rb << 1); @@ -157,37 +152,41 @@ struct SkGlyph { } void toMask(SkMask* mask) const; - - /** Given a glyph which is has a mask format of LCD or VerticalLCD, take - the A8 plane in fImage and produce a valid LCD plane from it. - */ - void expandA8ToLCD() const; }; class SkScalerContext { public: enum Flags { - kFrameAndFill_Flag = 0x01, - kDevKernText_Flag = 0x02, - kGammaForBlack_Flag = 0x04, // illegal to set both Gamma flags - kGammaForWhite_Flag = 0x08, // illegal to set both Gamma flags + kFrameAndFill_Flag = 0x0001, + kDevKernText_Flag = 0x0002, + kEmbeddedBitmapText_Flag = 0x0004, + kEmbolden_Flag = 0x0008, + kSubpixelPositioning_Flag = 0x0010, + kAutohinting_Flag = 0x0020, + kVertical_Flag = 0x0040, + // together, these two flags resulting in a two bit value which matches // up with the SkPaint::Hinting enum. - kHintingBit1_Flag = 0x10, - kHintingBit2_Flag = 0x20, - kEmbeddedBitmapText_Flag = 0x40, - kEmbolden_Flag = 0x80, - kSubpixelPositioning_Flag = 0x100, - kAutohinting_Flag = 0x200, - // these should only ever be set if fMaskFormat is LCD - kLCD_Vertical_Flag = 0x400, // else Horizontal - kLCD_BGROrder_Flag = 0x800, // else RGB order + kHinting_Shift = 7, // to shift into the other flags above + kHintingBit1_Flag = 0x0080, + kHintingBit2_Flag = 0x0100, + + // these should only ever be set if fMaskFormat is LCD16 or LCD32 + kLCD_Vertical_Flag = 0x0200, // else Horizontal + kLCD_BGROrder_Flag = 0x0400, // else RGB order + + // luminance : 0 for black text, kLuminance_Max for white text + kLuminance_Shift = 11, // to shift into the other flags above + kLuminance_Bits = 3, // ensure Flags doesn't exceed 16bits }; -private: + + // computed values enum { - kHintingMask = kHintingBit1_Flag | kHintingBit2_Flag + kHinting_Mask = kHintingBit1_Flag | kHintingBit2_Flag, + kLuminance_Max = (1 << kLuminance_Bits) - 1, + kLuminance_Mask = kLuminance_Max << kLuminance_Shift, }; -public: + struct Rec { uint32_t fOrigFontID; uint32_t fFontID; @@ -207,19 +206,33 @@ public: void getSingleMatrix(SkMatrix*) const; SkPaint::Hinting getHinting() const { - return static_cast<SkPaint::Hinting>((fFlags & kHintingMask) >> 4); + unsigned hint = (fFlags & kHinting_Mask) >> kHinting_Shift; + return static_cast<SkPaint::Hinting>(hint); } void setHinting(SkPaint::Hinting hinting) { - fFlags = (fFlags & ~kHintingMask) | (hinting << 4); + fFlags = (fFlags & ~kHinting_Mask) | (hinting << kHinting_Shift); } - SkMask::Format getFormat() const { - return static_cast<SkMask::Format>(fMaskFormat); + unsigned getLuminanceBits() const { + return (fFlags & kLuminance_Mask) >> kLuminance_Shift; + } + + void setLuminanceBits(unsigned lum) { + SkASSERT(lum <= kLuminance_Max); + fFlags = (fFlags & ~kLuminance_Mask) | (lum << kLuminance_Shift); } - bool isLCD() const { - return SkMask::FormatIsLCD(this->getFormat()); + U8CPU getLuminanceByte() const { + SkASSERT(3 == kLuminance_Bits); + unsigned lum = this->getLuminanceBits(); + lum |= (lum << kLuminance_Bits); + lum |= (lum << kLuminance_Bits*2); + return lum >> (4*kLuminance_Bits - 8); + } + + SkMask::Format getFormat() const { + return static_cast<SkMask::Format>(fMaskFormat); } }; @@ -230,6 +243,10 @@ public: return (SkMask::Format)fRec.fMaskFormat; } + bool isSubpixel() const { + return SkToBool(fRec.fFlags & kSubpixelPositioning_Flag); + } + // remember our glyph offset/base void setBaseGlyphCount(unsigned baseGlyphCount) { fBaseGlyphCount = baseGlyphCount; @@ -240,7 +257,7 @@ public: fact correspond to a different font/context. In that case, we use the base-glyph-count to know how to translate back into local glyph space. */ - uint16_t charToGlyphID(SkUnichar uni); + uint16_t charToGlyphID(SkUnichar uni); /** Map the glyphID to its glyph index, and then to its char code. Unmapped glyphs return zero. @@ -255,6 +272,10 @@ public: void getFontMetrics(SkPaint::FontMetrics* mX, SkPaint::FontMetrics* mY); +#ifdef SK_BUILD_FOR_ANDROID + unsigned getBaseGlyphCount(SkUnichar charCode); +#endif + static inline void MakeRec(const SkPaint&, const SkMatrix*, Rec* rec); static SkScalerContext* Create(const SkDescriptor*); @@ -273,12 +294,18 @@ protected: // default impl returns 0, indicating failure. virtual SkUnichar generateGlyphToChar(uint16_t); + void forceGenerateImageFromPath() { fGenerateImageFromPath = true; } + private: SkPathEffect* fPathEffect; SkMaskFilter* fMaskFilter; SkRasterizer* fRasterizer; SkScalar fDevFrameWidth; + // if this is set, we draw the image from a path, rather than + // calling generateImage. + bool fGenerateImageFromPath; + void internalGetPath(const SkGlyph& glyph, SkPath* fillPath, SkPath* devPath, SkMatrix* fillToDevMatrix); @@ -298,5 +325,21 @@ private: #define kMaskFilter_SkDescriptorTag SkSetFourByteTag('m', 's', 'k', 'f') #define kRasterizer_SkDescriptorTag SkSetFourByteTag('r', 'a', 's', 't') +/////////////////////////////////////////////////////////////////////////////// + +enum SkAxisAlignment { + kNone_SkAxisAlignment, + kX_SkAxisAlignment, + kY_SkAxisAlignment +}; + +/** + * Return the axis (if any) that the baseline for horizontal text will land on + * after running through the specified matrix. + * + * As an example, the identity matrix will return kX_SkAxisAlignment + */ +SkAxisAlignment SkComputeAxisAlignmentForHText(const SkMatrix& matrix); + #endif diff --git a/include/core/SkScan.h b/include/core/SkScan.h index 31d4845..61ba1b0 100644 --- a/include/core/SkScan.h +++ b/include/core/SkScan.h @@ -1,25 +1,18 @@ -/* libs/graphics/sgl/SkScan.h -** -** Copyright 2011, The Android Open Source Project -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ + +/* + * Copyright 2011 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkScan_DEFINED #define SkScan_DEFINED #include "SkRect.h" +class SkRasterClip; class SkRegion; class SkBlitter; class SkPath; @@ -31,57 +24,74 @@ typedef SkIRect SkXRect; class SkScan { public: - static void FillIRect(const SkIRect&, const SkRegion* clip, SkBlitter*); - static void FillXRect(const SkXRect&, const SkRegion* clip, SkBlitter*); + static void FillPath(const SkPath&, const SkIRect&, SkBlitter*); + /////////////////////////////////////////////////////////////////////////// + // rasterclip + + static void FillIRect(const SkIRect&, const SkRasterClip&, SkBlitter*); + static void FillXRect(const SkXRect&, const SkRasterClip&, SkBlitter*); #ifdef SK_SCALAR_IS_FIXED - static void FillRect(const SkRect& rect, const SkRegion* clip, + static void FillRect(const SkRect& rect, const SkRasterClip& clip, SkBlitter* blitter) { SkScan::FillXRect(*(const SkXRect*)&rect, clip, blitter); } -#else - static void FillRect(const SkRect&, const SkRegion* clip, SkBlitter*); -#endif - static void FillPath(const SkPath&, const SkRegion& clip, SkBlitter*); - - static void FillTriangle(const SkPoint pts[], const SkRegion*, SkBlitter*); - static void FillTriangle(const SkPoint& a, const SkPoint& b, - const SkPoint& c, const SkRegion* clip, + static void AntiFillRect(const SkRect& rect, const SkRasterClip& clip, SkBlitter* blitter) { - SkPoint pts[3]; - pts[0] = a; - pts[1] = b; - pts[2] = c; - FillTriangle(pts, clip, blitter); + SkScan::AntiFillXRect(*(const SkXRect*)&rect, clip, blitter); } - - static void HairLine(const SkPoint&, const SkPoint&, const SkRegion*, +#else + static void FillRect(const SkRect&, const SkRasterClip&, SkBlitter*); + static void AntiFillRect(const SkRect&, const SkRasterClip&, SkBlitter*); +#endif + static void AntiFillXRect(const SkXRect&, const SkRasterClip&, SkBlitter*); + static void FillPath(const SkPath&, const SkRasterClip&, SkBlitter*); + static void AntiFillPath(const SkPath&, const SkRasterClip&, SkBlitter*); + static void FrameRect(const SkRect&, const SkPoint& strokeSize, + const SkRasterClip&, SkBlitter*); + static void AntiFrameRect(const SkRect&, const SkPoint& strokeSize, + const SkRasterClip&, SkBlitter*); + static void FillTriangle(const SkPoint pts[], const SkRasterClip&, SkBlitter*); + static void HairLine(const SkPoint&, const SkPoint&, const SkRasterClip&, SkBlitter*); - static void HairRect(const SkRect&, const SkRegion* clip, SkBlitter*); - static void HairPath(const SkPath&, const SkRegion* clip, SkBlitter*); + static void AntiHairLine(const SkPoint&, const SkPoint&, const SkRasterClip&, + SkBlitter*); + static void HairRect(const SkRect&, const SkRasterClip&, SkBlitter*); + static void AntiHairRect(const SkRect&, const SkRasterClip&, SkBlitter*); + static void HairPath(const SkPath&, const SkRasterClip&, SkBlitter*); + static void AntiHairPath(const SkPath&, const SkRasterClip&, SkBlitter*); + +private: + friend class SkAAClip; + friend class SkRegion; - static void AntiFillXRect(const SkXRect&, const SkRegion* clip, SkBlitter*); + static void FillIRect(const SkIRect&, const SkRegion* clip, SkBlitter*); + static void FillXRect(const SkXRect&, const SkRegion* clip, SkBlitter*); #ifdef SK_SCALAR_IS_FIXED - static void AntiFillRect(const SkRect& rect, const SkRegion* clip, + static void FillRect(const SkRect& rect, const SkRegion* clip, SkBlitter* blitter) { + SkScan::FillXRect(*(const SkXRect*)&rect, clip, blitter); + } + static void AntiFillRect(const SkRect& rect, const SkRegion* clip, + SkBlitter* blitter) { SkScan::AntiFillXRect(*(const SkXRect*)&rect, clip, blitter); } #else + static void FillRect(const SkRect&, const SkRegion* clip, SkBlitter*); static void AntiFillRect(const SkRect&, const SkRegion* clip, SkBlitter*); #endif + static void AntiFillXRect(const SkXRect&, const SkRegion*, SkBlitter*); + static void FillPath(const SkPath&, const SkRegion& clip, SkBlitter*); + static void AntiFillPath(const SkPath&, const SkRegion& clip, SkBlitter*, + bool forceRLE = false); + static void FillTriangle(const SkPoint pts[], const SkRegion*, SkBlitter*); - static void AntiFillPath(const SkPath&, const SkRegion& clip, SkBlitter*); - - static void AntiHairLine(const SkPoint&, const SkPoint&, const SkRegion*, - SkBlitter*); - static void AntiHairRect(const SkRect&, const SkRegion* clip, SkBlitter*); - static void AntiHairPath(const SkPath&, const SkRegion* clip, SkBlitter*); - - // draws with a miter-join - static void FrameRect(const SkRect&, const SkPoint& strokeSize, - const SkRegion*, SkBlitter*); static void AntiFrameRect(const SkRect&, const SkPoint& strokeSize, const SkRegion*, SkBlitter*); + static void HairLineRgn(const SkPoint&, const SkPoint&, const SkRegion*, + SkBlitter*); + static void AntiHairLineRgn(const SkPoint&, const SkPoint&, const SkRegion*, + SkBlitter*); }; /** Assign an SkXRect from a SkIRect, by promoting the src rect's coordinates diff --git a/include/core/SkShader.h b/include/core/SkShader.h index cf1d4e9..7c5be06 100644 --- a/include/core/SkShader.h +++ b/include/core/SkShader.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkShader_DEFINED #define SkShader_DEFINED @@ -104,6 +97,15 @@ public: virtual uint32_t getFlags() { return 0; } /** + * Returns true if the shader is guaranteed to produce only opaque + * colors, subject to the SkPaint using the shader to apply an opaque + * alpha value. Subclasses should override this to allow some + * optimizations. isOpaque() can be called at any time, unlike getFlags, + * which only works properly when the context is set. + */ + virtual bool isOpaque() const { return false; } + + /** * Return the alpha associated with the data returned by shadeSpan16(). If * kHasSpan16_Flag is not set, this value is meaningless. */ @@ -277,7 +279,7 @@ public: static SkShader* CreateBitmapShader(const SkBitmap& src, TileMode tmx, TileMode tmy); - virtual void flatten(SkFlattenableWriteBuffer& ); + virtual void flatten(SkFlattenableWriteBuffer& ) SK_OVERRIDE; protected: enum MatrixClass { kLinear_MatrixClass, // no perspective diff --git a/include/core/SkShape.h b/include/core/SkShape.h index 6cee70e..c7cf9ec 100644 --- a/include/core/SkShape.h +++ b/include/core/SkShape.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkShape_DEFINED #define SkShape_DEFINED @@ -31,6 +38,8 @@ public: // public for Registrar static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: virtual void onDraw(SkCanvas*); diff --git a/include/core/SkSize.h b/include/core/SkSize.h index 8371c9b..12dbeae 100644 --- a/include/core/SkSize.h +++ b/include/core/SkSize.h @@ -1,4 +1,11 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkSize_DEFINED #define SkSize_DEFINED diff --git a/include/core/SkStream.h b/include/core/SkStream.h index c3d8185..90d2357 100644 --- a/include/core/SkStream.h +++ b/include/core/SkStream.h @@ -1,25 +1,20 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkStream_DEFINED #define SkStream_DEFINED #include "SkRefCnt.h" #include "SkScalar.h" +class SkData; + class SK_API SkStream : public SkRefCnt { public: virtual ~SkStream(); @@ -100,6 +95,8 @@ public: bool writePackedUInt(size_t); bool writeStream(SkStream* input, size_t length); + + bool writeData(const SkData*); }; //////////////////////////////////////////////////////////////////////////////////////// @@ -127,9 +124,9 @@ public: */ void setPath(const char path[]); - virtual bool rewind(); - virtual size_t read(void* buffer, size_t size); - virtual const char* getFileName(); + virtual bool rewind() SK_OVERRIDE; + virtual size_t read(void* buffer, size_t size) SK_OVERRIDE; + virtual const char* getFileName() SK_OVERRIDE; private: SkFILE* fFILE; @@ -151,9 +148,9 @@ public: */ bool isValid() const { return fFD >= 0; } - virtual bool rewind(); - virtual size_t read(void* buffer, size_t size); - virtual const char* getFileName() { return NULL; } + virtual bool rewind() SK_OVERRIDE; + virtual size_t read(void* buffer, size_t size) SK_OVERRIDE; + virtual const char* getFileName() SK_OVERRIDE { return NULL; } private: int fFD; @@ -182,18 +179,31 @@ public: will be freed with sk_free. */ void setMemoryOwned(const void* data, size_t length); + + /** + * Return the stream's data in a SkData. The caller must call unref() when + * it is finished using the data. + */ + SkData* copyToData() const; + + /** + * Use the specified data as the memory for this stream. The stream will + * call ref() on the data (assuming it is not null). The function returns + * the data parameter as a convenience. + */ + SkData* setData(SkData*); + void skipToAlign4(); - virtual bool rewind(); - virtual size_t read(void* buffer, size_t size); - virtual const void* getMemoryBase(); + virtual bool rewind() SK_OVERRIDE; + virtual size_t read(void* buffer, size_t size) SK_OVERRIDE; + virtual const void* getMemoryBase() SK_OVERRIDE; const void* getAtPos(); size_t seek(size_t offset); size_t peek() const { return fOffset; } private: - const void* fSrc; - size_t fSize, fOffset; - SkBool8 fWeOwnTheData; + SkData* fData; + size_t fOffset; }; /** \class SkBufferStream @@ -220,10 +230,10 @@ public: SkBufferStream(SkStream* proxy, void* buffer, size_t bufferSize); virtual ~SkBufferStream(); - virtual bool rewind(); - virtual const char* getFileName(); - virtual size_t read(void* buffer, size_t size); - virtual const void* getMemoryBase(); + virtual bool rewind() SK_OVERRIDE; + virtual const char* getFileName() SK_OVERRIDE; + virtual size_t read(void* buffer, size_t size) SK_OVERRIDE; + virtual const void* getMemoryBase() SK_OVERRIDE; private: enum { @@ -252,8 +262,8 @@ public: */ bool isValid() const { return fFILE != NULL; } - virtual bool write(const void* buffer, size_t size); - virtual void flush(); + virtual bool write(const void* buffer, size_t size) SK_OVERRIDE; + virtual void flush() SK_OVERRIDE; private: SkFILE* fFILE; }; @@ -261,7 +271,7 @@ private: class SkMemoryWStream : public SkWStream { public: SkMemoryWStream(void* buffer, size_t size); - virtual bool write(const void* buffer, size_t size); + virtual bool write(const void* buffer, size_t size) SK_OVERRIDE; private: char* fBuffer; @@ -273,24 +283,24 @@ class SK_API SkDynamicMemoryWStream : public SkWStream { public: SkDynamicMemoryWStream(); virtual ~SkDynamicMemoryWStream(); - virtual bool write(const void* buffer, size_t size); + + virtual bool write(const void* buffer, size_t size) SK_OVERRIDE; // random access write // modifies stream and returns true if offset + size is less than or equal to getOffset() bool write(const void* buffer, size_t offset, size_t size); bool read(void* buffer, size_t offset, size_t size); size_t getOffset() const { return fBytesWritten; } + size_t bytesWritten() const { return fBytesWritten; } // copy what has been written to the stream into dst - void copyTo(void* dst) const; - /* return a cache of the flattened data returned by copyTo(). - This copy is only valid until the next call to write(). - The memory is managed by the stream class. - */ - const char* getStream() const; + void copyTo(void* dst) const; + + /** + * Return a copy of the data written so far. This call is responsible for + * calling unref() when they are finished with the data. + */ + SkData* copyToData() const; - // same as getStream, but additionally detach the flattened datat - const char* detach(); - // reset the stream to its original state void reset(); void padToAlign4(); @@ -299,15 +309,17 @@ private: Block* fHead; Block* fTail; size_t fBytesWritten; - mutable char* fCopyToCache; + mutable SkData* fCopy; // is invalidated if we write after it is created + + void invalidateCopy(); }; class SkDebugWStream : public SkWStream { public: // overrides - virtual bool write(const void* buffer, size_t size); - virtual void newline(); + virtual bool write(const void* buffer, size_t size) SK_OVERRIDE; + virtual void newline() SK_OVERRIDE; }; // for now diff --git a/include/core/SkString.h b/include/core/SkString.h index 0295b75..3fa367b 100644 --- a/include/core/SkString.h +++ b/include/core/SkString.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkString_DEFINED #define SkString_DEFINED @@ -73,7 +66,7 @@ public: SkString(const SkString&); ~SkString(); - bool isEmpty() const { return fRec->fLength == 0; } + bool isEmpty() const { return 0 == fRec->fLength; } size_t size() const { return (size_t) fRec->fLength; } const char* c_str() const { return fRec->data(); } char operator[](size_t n) const { return this->c_str()[n]; } @@ -89,19 +82,19 @@ public: return SkStrEndsWith(fRec->data(), suffix); } - friend int operator==(const SkString& a, const SkString& b) { + friend bool operator==(const SkString& a, const SkString& b) { return a.equals(b); } - friend int operator!=(const SkString& a, const SkString& b) { + friend bool operator!=(const SkString& a, const SkString& b) { return !a.equals(b); } // these methods edit the string - SkString& operator=(const SkString&); - SkString& operator=(const char text[]); + SkString& operator=(const SkString&); + SkString& operator=(const char text[]); - char* writable_str(); + char* writable_str(); char& operator[](size_t n) { return this->writable_str()[n]; } void reset(); @@ -158,8 +151,8 @@ public: private: struct Rec { public: - uint16_t fLength; - uint16_t fRefCnt; + size_t fLength; + int32_t fRefCnt; char fBeginningOfData; char* data() { return &fBeginningOfData; } @@ -175,7 +168,7 @@ private: #endif static const Rec gEmptyRec; - static Rec* AllocRec(const char text[], U16CPU len); + static Rec* AllocRec(const char text[], size_t len); static Rec* RefRec(Rec*); }; @@ -197,4 +190,7 @@ private: uint16_t* fUCS2; }; +/// Creates a new string and writes into it using a printf()-style format. +SkString SkStringPrintf(const char* format, ...); + #endif diff --git a/include/core/SkStroke.h b/include/core/SkStroke.h index b593b69..d055b83 100644 --- a/include/core/SkStroke.h +++ b/include/core/SkStroke.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkStroke_DEFINED #define SkStroke_DEFINED diff --git a/include/core/SkTArray.h b/include/core/SkTArray.h new file mode 100644 index 0000000..577e860 --- /dev/null +++ b/include/core/SkTArray.h @@ -0,0 +1,415 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkTArray_DEFINED +#define SkTArray_DEFINED + +#include <new> +#include "SkTypes.h" +#include "SkTemplates.h" + +template <typename T, bool MEM_COPY = false> class SkTArray; + +namespace SkTArrayExt { + +template<typename T> +inline void copy(SkTArray<T, true>* self, const T* array) { + memcpy(self->fMemArray, array, self->fCount * sizeof(T)); +} +template<typename T> +inline void copyAndDelete(SkTArray<T, true>* self, char* newMemArray) { + memcpy(newMemArray, self->fMemArray, self->fCount * sizeof(T)); +} + +template<typename T> +inline void copy(SkTArray<T, false>* self, const T* array) { + for (int i = 0; i < self->fCount; ++i) { + new (self->fItemArray + i) T(array[i]); + } +} +template<typename T> +inline void copyAndDelete(SkTArray<T, false>* self, char* newMemArray) { + for (int i = 0; i < self->fCount; ++i) { + new (newMemArray + sizeof(T) * i) T(self->fItemArray[i]); + self->fItemArray[i].~T(); + } +} + +} + +/** When MEM_COPY is true T will be bit copied when moved. + When MEM_COPY is false, T will be copy constructed / destructed. + In all cases T's constructor will be called on allocation, + and its destructor will be called from this object's destructor. +*/ +template <typename T, bool MEM_COPY> class SkTArray { +public: + /** + * Creates an empty array with no initial storage + */ + SkTArray() { + fCount = 0; + fReserveCount = gMIN_ALLOC_COUNT; + fAllocCount = 0; + fMemArray = NULL; + fPreAllocMemArray = NULL; + } + + /** + * Creates an empty array that will preallocate space for reserveCount + * elements. + */ + explicit SkTArray(int reserveCount) { + this->init(NULL, 0, NULL, reserveCount); + } + + /** + * Copies one array to another. The new array will be heap allocated. + */ + explicit SkTArray(const SkTArray& array) { + this->init(array.fItemArray, array.fCount, NULL, 0); + } + + /** + * Creates a SkTArray by copying contents of a standard C array. The new + * array will be heap allocated. Be careful not to use this constructor + * when you really want the (void*, int) version. + */ + SkTArray(const T* array, int count) { + this->init(array, count, NULL, 0); + } + + /** + * assign copy of array to this + */ + SkTArray& operator =(const SkTArray& array) { + for (int i = 0; i < fCount; ++i) { + fItemArray[i].~T(); + } + fCount = 0; + checkRealloc((int)array.count()); + fCount = array.count(); + SkTArrayExt::copy(this, static_cast<const T*>(array.fMemArray)); + return *this; + } + + virtual ~SkTArray() { + for (int i = 0; i < fCount; ++i) { + fItemArray[i].~T(); + } + if (fMemArray != fPreAllocMemArray) { + sk_free(fMemArray); + } + } + + /** + * Resets to count() == 0 + */ + void reset() { this->pop_back_n(fCount); } + + /** + * Number of elements in the array. + */ + int count() const { return fCount; } + + /** + * Is the array empty. + */ + bool empty() const { return !fCount; } + + /** + * Adds 1 new default-constructed T value and returns in by reference. Note + * the reference only remains valid until the next call that adds or removes + * elements. + */ + T& push_back() { + checkRealloc(1); + new ((char*)fMemArray+sizeof(T)*fCount) T; + ++fCount; + return fItemArray[fCount-1]; + } + + /** + * Version of above that uses a copy constructor to initialize the new item + */ + T& push_back(const T& t) { + checkRealloc(1); + new ((char*)fMemArray+sizeof(T)*fCount) T(t); + ++fCount; + return fItemArray[fCount-1]; + } + + /** + * Allocates n more default T values, and returns the address of the start + * of that new range. Note: this address is only valid until the next API + * call made on the array that might add or remove elements. + */ + T* push_back_n(int n) { + SkASSERT(n >= 0); + checkRealloc(n); + for (int i = 0; i < n; ++i) { + new (fItemArray + fCount + i) T; + } + fCount += n; + return fItemArray + fCount - n; + } + + /** + * Version of above that uses a copy constructor to initialize all n items + * to the same T. + */ + T* push_back_n(int n, const T& t) { + SkASSERT(n >= 0); + checkRealloc(n); + for (int i = 0; i < n; ++i) { + new (fItemArray + fCount + i) T(t); + } + fCount += n; + return fItemArray + fCount - n; + } + + /** + * Version of above that uses a copy constructor to initialize the n items + * to separate T values. + */ + T* push_back_n(int n, const T t[]) { + SkASSERT(n >= 0); + checkRealloc(n); + for (int i = 0; i < n; ++i) { + new (fItemArray + fCount + i) T(t[i]); + } + fCount += n; + return fItemArray + fCount - n; + } + + /** + * Removes the last element. Not safe to call when count() == 0. + */ + void pop_back() { + SkASSERT(fCount > 0); + --fCount; + fItemArray[fCount].~T(); + checkRealloc(0); + } + + /** + * Removes the last n elements. Not safe to call when count() < n. + */ + void pop_back_n(int n) { + SkASSERT(n >= 0); + SkASSERT(fCount >= n); + fCount -= n; + for (int i = 0; i < n; ++i) { + fItemArray[i].~T(); + } + checkRealloc(0); + } + + /** + * Pushes or pops from the back to resize. Pushes will be default + * initialized. + */ + void resize_back(int newCount) { + SkASSERT(newCount >= 0); + + if (newCount > fCount) { + push_back_n(newCount - fCount); + } else if (newCount < fCount) { + pop_back_n(fCount - newCount); + } + } + + /** + * Get the i^th element. + */ + T& operator[] (int i) { + SkASSERT(i < fCount); + SkASSERT(i >= 0); + return fItemArray[i]; + } + + const T& operator[] (int i) const { + SkASSERT(i < fCount); + SkASSERT(i >= 0); + return fItemArray[i]; + } + + /** + * equivalent to operator[](0) + */ + T& front() { SkASSERT(fCount > 0); return fItemArray[0];} + + const T& front() const { SkASSERT(fCount > 0); return fItemArray[0];} + + /** + * equivalent to operator[](count() - 1) + */ + T& back() { SkASSERT(fCount); return fItemArray[fCount - 1];} + + const T& back() const { SkASSERT(fCount > 0); return fItemArray[fCount - 1];} + + /** + * equivalent to operator[](count()-1-i) + */ + T& fromBack(int i) { + SkASSERT(i >= 0); + SkASSERT(i < fCount); + return fItemArray[fCount - i - 1]; + } + + const T& fromBack(int i) const { + SkASSERT(i >= 0); + SkASSERT(i < fCount); + return fItemArray[fCount - i - 1]; + } + +protected: + /** + * Creates an empty array that will use the passed storage block until it + * is insufficiently large to hold the entire array. + */ + template <int N> + SkTArray(SkAlignedSTStorage<N,T>* storage) { + this->init(NULL, 0, storage->get(), N); + } + + /** + * Copy another array, using preallocated storage if preAllocCount >= + * array.count(). Otherwise storage will only be used when array shrinks + * to fit. + */ + template <int N> + SkTArray(const SkTArray& array, SkAlignedSTStorage<N,T>* storage) { + this->init(array.fItemArray, array.fCount, storage->get(), N); + } + + /** + * Copy a C array, using preallocated storage if preAllocCount >= + * count. Otherwise storage will only be used when array shrinks + * to fit. + */ + template <int N> + SkTArray(const T* array, int count, SkAlignedSTStorage<N,T>* storage) { + this->init(array, count, storage->get(), N); + } + + void init(const T* array, int count, + void* preAllocStorage, int preAllocOrReserveCount) { + SkASSERT(count >= 0); + SkASSERT(preAllocOrReserveCount >= 0); + fCount = count; + fReserveCount = (preAllocOrReserveCount > 0) ? + preAllocOrReserveCount : + gMIN_ALLOC_COUNT; + fPreAllocMemArray = preAllocStorage; + if (fReserveCount >= fCount && + NULL != preAllocStorage) { + fAllocCount = fReserveCount; + fMemArray = preAllocStorage; + } else { + fAllocCount = SkMax32(fCount, fReserveCount); + fMemArray = sk_malloc_throw(fAllocCount * sizeof(T)); + } + + SkTArrayExt::copy(this, array); + } + +private: + + static const int gMIN_ALLOC_COUNT = 8; + + inline void checkRealloc(int delta) { + SkASSERT(fCount >= 0); + SkASSERT(fAllocCount >= 0); + + SkASSERT(-delta <= fCount); + + int newCount = fCount + delta; + int newAllocCount = fAllocCount; + + if (newCount > fAllocCount) { + newAllocCount = SkMax32(newCount + ((newCount + 1) >> 1), + fReserveCount); + } else if (newCount < fAllocCount / 3) { + newAllocCount = SkMax32(fAllocCount / 2, fReserveCount); + } + + if (newAllocCount != fAllocCount) { + + fAllocCount = newAllocCount; + char* newMemArray; + + if (fAllocCount == fReserveCount && NULL != fPreAllocMemArray) { + newMemArray = (char*) fPreAllocMemArray; + } else { + newMemArray = (char*) sk_malloc_throw(fAllocCount*sizeof(T)); + } + + SkTArrayExt::copyAndDelete<T>(this, newMemArray); + + if (fMemArray != fPreAllocMemArray) { + sk_free(fMemArray); + } + fMemArray = newMemArray; + } + } + + template<typename X> friend void SkTArrayExt::copy(SkTArray<X, true>* that, const X*); + template<typename X> friend void SkTArrayExt::copyAndDelete(SkTArray<X, true>* that, char*); + + template<typename X> friend void SkTArrayExt::copy(SkTArray<X, false>* that, const X*); + template<typename X> friend void SkTArrayExt::copyAndDelete(SkTArray<X, false>* that, char*); + + int fReserveCount; + int fCount; + int fAllocCount; + void* fPreAllocMemArray; + union { + T* fItemArray; + void* fMemArray; + }; +}; + +/** + * Subclass of SkTArray that contains a preallocated memory block for the array. + */ +template <int N, typename T, bool DATA_TYPE = false> +class SkSTArray : public SkTArray<T, DATA_TYPE> { +private: + typedef SkTArray<T, DATA_TYPE> INHERITED; + +public: + SkSTArray() : INHERITED(&fStorage) { + } + + SkSTArray(const SkSTArray& array) + : INHERITED(array, &fStorage) { + } + + explicit SkSTArray(const INHERITED& array) + : INHERITED(array, &fStorage) { + } + + SkSTArray(const T* array, int count) + : INHERITED(array, count, &fStorage) { + } + + SkSTArray& operator= (const SkSTArray& array) { + return *this = *(const INHERITED*)&array; + } + + SkSTArray& operator= (const INHERITED& array) { + INHERITED::operator=(array); + return *this; + } + +private: + SkAlignedSTStorage<N,T> fStorage; +}; + +#endif + diff --git a/include/core/SkTDArray.h b/include/core/SkTDArray.h index c64d773..5f62203 100644 --- a/include/core/SkTDArray.h +++ b/include/core/SkTDArray.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTDArray_DEFINED #define SkTDArray_DEFINED @@ -71,7 +64,7 @@ public: return *this; } - friend int operator==(const SkTDArray<T>& a, const SkTDArray<T>& b) { + friend bool operator==(const SkTDArray<T>& a, const SkTDArray<T>& b) { return a.fCount == b.fCount && (a.fCount == 0 || !memcmp(a.fArray, b.fArray, a.fCount * sizeof(T))); @@ -98,7 +91,17 @@ public: } bool isEmpty() const { return fCount == 0; } + + /** + * Return the number of elements in the array + */ int count() const { return fCount; } + + /** + * return the number of bytes in the array: count * sizeof(T) + */ + size_t bytes() const { return fCount * sizeof(T); } + T* begin() const { return fArray; } T* end() const { return fArray ? fArray + fCount : NULL; } T& operator[](int index) const { diff --git a/include/core/SkTDStack.h b/include/core/SkTDStack.h index 321c138..be34e01 100644 --- a/include/core/SkTDStack.h +++ b/include/core/SkTDStack.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTDStack_DEFINED #define SkTDStack_DEFINED @@ -21,18 +14,16 @@ template <typename T> class SkTDStack : SkNoncopyable { public: - SkTDStack() : fCount(0), fTotalCount(0) - { + SkTDStack() : fCount(0), fTotalCount(0) { fInitialRec.fNext = NULL; fRec = &fInitialRec; // fCount = kSlotCount; } - ~SkTDStack() - { + + ~SkTDStack() { Rec* rec = fRec; - while (rec != &fInitialRec) - { + while (rec != &fInitialRec) { Rec* next = rec->fNext; sk_free(rec); rec = next; @@ -43,11 +34,9 @@ public: int depth() const { return fTotalCount; } bool empty() const { return fTotalCount == 0; } - T* push() - { + T* push() { SkASSERT(fCount <= kSlotCount); - if (fCount == kSlotCount) - { + if (fCount == kSlotCount) { Rec* rec = (Rec*)sk_malloc_throw(sizeof(Rec)); rec->fNext = fRec; fRec = rec; @@ -56,48 +45,48 @@ public: ++fTotalCount; return &fRec->fSlots[fCount++]; } + void push(const T& elem) { *this->push() = elem; } - const T& index(int idx) const - { + + const T& index(int idx) const { SkASSERT(fRec && fCount > idx); return fRec->fSlots[fCount - idx - 1]; - } - T& index(int idx) - { + } + + T& index(int idx) { SkASSERT(fRec && fCount > idx); return fRec->fSlots[fCount - idx - 1]; - } - const T& top() const - { + } + + const T& top() const { SkASSERT(fRec && fCount > 0); return fRec->fSlots[fCount - 1]; } - T& top() - { + + T& top() { SkASSERT(fRec && fCount > 0); return fRec->fSlots[fCount - 1]; } - void pop(T* elem) - { - if (elem) + + void pop(T* elem) { + if (elem) { *elem = fRec->fSlots[fCount - 1]; + } this->pop(); } - void pop() - { + + void pop() { SkASSERT(fCount > 0 && fRec); --fTotalCount; - if (--fCount == 0) - { - if (fRec != &fInitialRec) - { + if (--fCount == 0) { + if (fRec != &fInitialRec) { Rec* rec = fRec->fNext; sk_free(fRec); fCount = kSlotCount; fRec = rec; - } - else + } else { SkASSERT(fTotalCount == 0); + } } } diff --git a/include/core/SkTDict.h b/include/core/SkTDict.h index 0b92779..3620899 100644 --- a/include/core/SkTDict.h +++ b/include/core/SkTDict.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTDict_DEFINED #define SkTDict_DEFINED diff --git a/include/core/SkTLazy.h b/include/core/SkTLazy.h index fecc975..9cfaccb 100644 --- a/include/core/SkTLazy.h +++ b/include/core/SkTLazy.h @@ -1,24 +1,18 @@ -/* - Copyright 2011 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTLazy_DEFINED #define SkTLazy_DEFINED #include "SkTypes.h" +#include <new> /** * Efficient way to defer allocating/initializing a class until it is needed @@ -35,14 +29,15 @@ public: } SkTLazy(const SkTLazy<T>& src) : fPtr(NULL) { - const T* ptr = src.get(); - if (ptr) { - fPtr = new (fStorage) T(*ptr); + if (src.isValid()) { + fPtr = new (fStorage) T(*src->get()); + } else { + fPtr = NULL; } } ~SkTLazy() { - if (fPtr) { + if (this->isValid()) { fPtr->~T(); } } @@ -54,13 +49,13 @@ public: * always returned. */ T* init() { - if (fPtr) { + if (this->isValid()) { fPtr->~T(); } - fPtr = new (fStorage) T; + fPtr = new (SkTCast<T*>(fStorage)) T; return fPtr; } - + /** * Copy src into this, and return a pointer to a copy of it. Note this * will always return the same pointer, so if it is called on a lazy that @@ -68,19 +63,25 @@ public: * contents. */ T* set(const T& src) { - if (fPtr) { + if (this->isValid()) { *fPtr = src; } else { - fPtr = new (fStorage) T(src); + fPtr = new (SkTCast<T*>(fStorage)) T(src); } return fPtr; } + + /** + * Returns true if a valid object has been initialized in the SkTLazy, + * false otherwise. + */ + bool isValid() const { return NULL != fPtr; } /** * Returns either NULL, or a copy of the object that was passed to * set() or the constructor. */ - T* get() const { return fPtr; } + T* get() const { SkASSERT(this->isValid()); return fPtr; } private: T* fPtr; // NULL or fStorage diff --git a/include/core/SkTRegistry.h b/include/core/SkTRegistry.h index 78c5a07..34fcffd 100644 --- a/include/core/SkTRegistry.h +++ b/include/core/SkTRegistry.h @@ -1,19 +1,12 @@ + /* - * Copyright 2009, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2009 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTRegistry_DEFINED #define SkTRegistry_DEFINED @@ -28,7 +21,7 @@ public: typedef T (*Factory)(P); SkTRegistry(Factory fact) { -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID // work-around for double-initialization bug { SkTRegistry* reg = gHead; diff --git a/include/core/SkTScopedPtr.h b/include/core/SkTScopedPtr.h index 1e5d4c4..580d72f 100644 --- a/include/core/SkTScopedPtr.h +++ b/include/core/SkTScopedPtr.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2011 Google Inc. * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTScopedPtr_DEFINED #define SkTScopedPtr_DEFINED diff --git a/include/core/SkTSearch.h b/include/core/SkTSearch.h index e208071..d5ab18c 100644 --- a/include/core/SkTSearch.h +++ b/include/core/SkTSearch.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTSearch_DEFINED #define SkTSearch_DEFINED diff --git a/include/core/SkTemplates.h b/include/core/SkTemplates.h index 55109bf..03f0892 100644 --- a/include/core/SkTemplates.h +++ b/include/core/SkTemplates.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTemplates_DEFINED #define SkTemplates_DEFINED @@ -179,36 +172,88 @@ private: */ template <typename T> class SkAutoTMalloc : SkNoncopyable { public: - SkAutoTMalloc(size_t count) - { + SkAutoTMalloc(size_t count) { fPtr = (T*)sk_malloc_flags(count * sizeof(T), SK_MALLOC_THROW | SK_MALLOC_TEMP); } - ~SkAutoTMalloc() - { + + ~SkAutoTMalloc() { sk_free(fPtr); } + + // doesn't preserve contents + void reset (size_t count) { + sk_free(fPtr); + fPtr = fPtr = (T*)sk_malloc_flags(count * sizeof(T), SK_MALLOC_THROW | SK_MALLOC_TEMP); + } + T* get() const { return fPtr; } + operator T*() { + return fPtr; + } + + operator const T*() const { + return fPtr; + } + + T& operator[](int index) { + return fPtr[index]; + } + + const T& operator[](int index) const { + return fPtr[index]; + } + private: T* fPtr; }; -template <size_t N, typename T> class SkAutoSTMalloc : SkNoncopyable { +template <size_t N, typename T> class SK_API SkAutoSTMalloc : SkNoncopyable { public: - SkAutoSTMalloc(size_t count) - { - if (count <= N) + SkAutoSTMalloc(size_t count) { + if (count <= N) { fPtr = fTStorage; - else + } else { fPtr = (T*)sk_malloc_flags(count * sizeof(T), SK_MALLOC_THROW | SK_MALLOC_TEMP); + } } - ~SkAutoSTMalloc() - { - if (fPtr != fTStorage) + + ~SkAutoSTMalloc() { + if (fPtr != fTStorage) { sk_free(fPtr); + } } + + // doesn't preserve contents + void reset(size_t count) { + if (fPtr != fTStorage) { + sk_free(fPtr); + } + if (count <= N) { + fPtr = fTStorage; + } else { + fPtr = (T*)sk_malloc_flags(count * sizeof(T), SK_MALLOC_THROW | SK_MALLOC_TEMP); + } + } + T* get() const { return fPtr; } + operator T*() { + return fPtr; + } + + operator const T*() const { + return fPtr; + } + + T& operator[](int index) { + return fPtr[index]; + } + + const T& operator[](int index) const { + return fPtr[index]; + } + private: T* fPtr; union { @@ -217,5 +262,37 @@ private: }; }; +/** + * Reserves memory that is aligned on double and pointer boundaries. + * Hopefully this is sufficient for all practical purposes. + */ +template <size_t N> class SkAlignedSStorage : SkNoncopyable { +public: + void* get() { return fData; } +private: + union { + void* fPtr; + double fDouble; + char fData[N]; + }; +}; + +/** + * Reserves memory that is aligned on double and pointer boundaries. + * Hopefully this is sufficient for all practical purposes. Otherwise, + * we have to do some arcane trickery to determine alignment of non-POD + * types. Lifetime of the memory is the lifetime of the object. + */ +template <int N, typename T> class SkAlignedSTStorage : SkNoncopyable { +public: + /** + * Returns void* because this object does not initialize the + * memory. Use placement new for types that require a cons. + */ + void* get() { return fStorage.get(); } +private: + SkAlignedSStorage<sizeof(T)*N> fStorage; +}; + #endif diff --git a/include/core/SkThread.h b/include/core/SkThread.h index 637492d..5f2da4a 100644 --- a/include/core/SkThread.h +++ b/include/core/SkThread.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkThread_DEFINED #define SkThread_DEFINED diff --git a/include/core/SkThread_platform.h b/include/core/SkThread_platform.h index f33f5dc..d83f3ed 100644 --- a/include/core/SkThread_platform.h +++ b/include/core/SkThread_platform.h @@ -1,30 +1,62 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkThread_platform_DEFINED #define SkThread_platform_DEFINED -#if defined(ANDROID) && !defined(SK_BUILD_FOR_ANDROID_NDK) +#if defined(SK_BUILD_FOR_ANDROID) -#include <utils/threads.h> +#if defined(SK_BUILD_FOR_ANDROID_NDK) + +#include <stdint.h> + +/* Just use the GCC atomic intrinsics. They're supported by the NDK toolchain, + * have reasonable performance, and provide full memory barriers + */ +static __attribute__((always_inline)) int32_t sk_atomic_inc(int32_t *addr) { + return __sync_fetch_and_add(addr, 1); +} + +static __attribute__((always_inline)) int32_t sk_atomic_dec(int32_t *addr) { + return __sync_fetch_and_add(addr, -1); +} + +#else // !SK_BUILD_FOR_ANDROID_NDK + +/* The platform atomics operations are slightly more efficient than the + * GCC built-ins, so use them. + */ #include <utils/Atomic.h> #define sk_atomic_inc(addr) android_atomic_inc(addr) #define sk_atomic_dec(addr) android_atomic_dec(addr) +#endif // !SK_BUILD_FOR_ANDROID_NDK + +#else // !SK_BUILD_FOR_ANDROID + +/** Implemented by the porting layer, this function adds 1 to the int specified + by the address (in a thread-safe manner), and returns the previous value. +*/ +SK_API int32_t sk_atomic_inc(int32_t* addr); +/** Implemented by the porting layer, this function subtracts 1 to the int + specified by the address (in a thread-safe manner), and returns the previous + value. +*/ +SK_API int32_t sk_atomic_dec(int32_t* addr); + +#endif // !SK_BUILD_FOR_ANDROID + +#if defined(SK_BUILD_FOR_ANDROID) && !defined(SK_BUILD_FOR_ANDROID_NDK) + +#include <utils/threads.h> + class SkMutex : android::Mutex { public: // if isGlobal is true, then ignore any errors in the platform-specific diff --git a/include/core/SkTime.h b/include/core/SkTime.h index 9ee7110..ede1fd9 100644 --- a/include/core/SkTime.h +++ b/include/core/SkTime.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTime_DEFINED #define SkTime_DEFINED diff --git a/include/core/SkTrace.h b/include/core/SkTrace.h new file mode 100644 index 0000000..2d48799 --- /dev/null +++ b/include/core/SkTrace.h @@ -0,0 +1,47 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkTrace_DEFINED +#define SkTrace_DEFINED + +#ifdef SK_USER_TRACE_INCLUDE_FILE + +/* If your system embeds skia and has complex event logging, in + src/config/SkUserConfig.h: + - define the three SK_TRACE_EVENT macros to map to your system's + equivalents, + - define the name of the include file in SK_USER_TRACE_INCLUDE_FILE + A trivial example is given in src/utils/SkDebugTrace.h. + + All arguments are const char*. Skia typically passes the name of + the object and function (and sometimes region of interest within + the function) separated by double colons for 'event'. + + SK_TRACE_EVENT1 and SK_TRACE_EVENT2 take one or two arbitrary + name-value pairs that you also want to log. SkStringPrintf() is useful + for formatting these values. + + For example: + SK_TRACE_EVENT0("GrContext::createAndLockTexture"); + SK_TRACE_EVENT1("GrDefaultPathRenderer::onDrawPath::renderPasses", + "verts", SkStringPrintf("%i", vert - base).c_str()); +*/ + + #include SK_USER_TRACE_INCLUDE_FILE + +#else + + #define SK_TRACE_EVENT0(event) + #define SK_TRACE_EVENT1(event, name1, value1) + #define SK_TRACE_EVENT2(event, name1, value1, name2, value2) + +#endif + +#endif + + diff --git a/include/core/SkTypeface.h b/include/core/SkTypeface.h index e13a21d..03ed11c 100644 --- a/include/core/SkTypeface.h +++ b/include/core/SkTypeface.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTypeface_DEFINED #define SkTypeface_DEFINED @@ -141,10 +134,17 @@ public: /** Retrieve detailed typeface metrics. Used by the PDF backend. @param perGlyphInfo Indicate what glyph specific information (advances, names, etc.) should be populated. + @param glyphIDs For per-glyph info, specify subset of the font by + giving glyph ids. Each integer represents a glyph + id. Passing NULL means all glyphs in the font. + @param glyphIDsCount Number of elements in subsetGlyphIds. Ignored if + glyphIDs is NULL. @return The returned object has already been referenced. */ SkAdvancedTypefaceMetrics* getAdvancedTypefaceMetrics( - SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo) const; + SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo, + const uint32_t* glyphIDs = NULL, + uint32_t glyphIDsCount = 0) const; protected: /** uniqueID must be unique (please!) and non-zero diff --git a/include/core/SkTypes.h b/include/core/SkTypes.h index 1a3a2e5..a584421 100644 --- a/include/core/SkTypes.h +++ b/include/core/SkTypes.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTypes_DEFINED #define SkTypes_DEFINED @@ -43,12 +36,12 @@ /** Called internally if we run out of memory. The platform implementation must not return, but should either throw an exception or otherwise exit. */ -extern void sk_out_of_memory(void); +SK_API extern void sk_out_of_memory(void); /** Called internally if we hit an unrecoverable error. The platform implementation must not return, but should either throw an exception or otherwise exit. */ -extern void sk_throw(void); +SK_API extern void sk_throw(void); enum { SK_MALLOC_TEMP = 0x01, //!< hint to sk_malloc that the requested memory will be freed in the scope of the stack frame @@ -62,21 +55,35 @@ enum { SK_API extern void* sk_malloc_flags(size_t size, unsigned flags); /** Same as sk_malloc(), but hard coded to pass SK_MALLOC_THROW as the flag */ -extern void* sk_malloc_throw(size_t size); +SK_API extern void* sk_malloc_throw(size_t size); /** Same as standard realloc(), but this one never returns null on failure. It will throw an exception if it fails. */ -extern void* sk_realloc_throw(void* buffer, size_t size); +SK_API extern void* sk_realloc_throw(void* buffer, size_t size); /** Free memory returned by sk_malloc(). It is safe to pass null. */ -SK_API extern void sk_free(void*); +SK_API extern void sk_free(void*); // bzero is safer than memset, but we can't rely on it, so... sk_bzero() static inline void sk_bzero(void* buffer, size_t size) { memset(buffer, 0, size); } -/////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +#ifdef SK_OVERRIDE_GLOBAL_NEW +#include <new> + +inline void* operator new(size_t size) { + return sk_malloc_throw(size); +} + +inline void operator delete(void* p) { + sk_free(p); +} +#endif + +/////////////////////////////////////////////////////////////////////////////// #define SK_INIT_TO_AVOID_WARNING = 0 @@ -86,6 +93,7 @@ static inline void sk_bzero(void* buffer, size_t size) { #ifdef SK_DEBUG #define SkASSERT(cond) SK_DEBUGBREAK(cond) + #define SkDEBUGFAIL(message) SkASSERT(false && message) #define SkDEBUGCODE(code) code #define SkDECLAREPARAM(type, var) , type var #define SkPARAM(var) , var @@ -94,6 +102,7 @@ static inline void sk_bzero(void* buffer, size_t size) { #define SkAssertResult(cond) SkASSERT(cond) #else #define SkASSERT(cond) + #define SkDEBUGFAIL(message) #define SkDEBUGCODE(code) #define SkDEBUGF(args) #define SkDECLAREPARAM(type, var) @@ -209,6 +218,8 @@ static inline bool SkIsU16(long x) { */ #define SkAlign4(x) (((x) + 3) >> 2 << 2) +#define SkIsAlign4(x) (((x) & 3) == 0) + typedef uint32_t SkFourByteTag; #define SkSetFourByteTag(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d)) @@ -394,20 +405,84 @@ private: SkAutoFree& operator=(const SkAutoFree&); }; -class SkAutoMalloc : public SkAutoFree { +/** + * Manage an allocated block of heap memory. This object is the sole manager of + * the lifetime of the block, so the caller must not call sk_free() or delete + * on the block, unless detach() was called. + */ +class SkAutoMalloc : public SkNoncopyable { public: - explicit SkAutoMalloc(size_t size) - : SkAutoFree(sk_malloc_flags(size, SK_MALLOC_THROW | SK_MALLOC_TEMP)) {} + explicit SkAutoMalloc(size_t size = 0) { + fPtr = size ? sk_malloc_throw(size) : NULL; + fSize = size; + } + + ~SkAutoMalloc() { + sk_free(fPtr); + } + + /** + * Passed to reset to specify what happens if the requested size is smaller + * than the current size (and the current block was dynamically allocated). + */ + enum OnShrink { + /** + * If the requested size is smaller than the current size, and the + * current block is dynamically allocated, free the old block and + * malloc a new block of the smaller size. + */ + kAlloc_OnShrink, + + /** + * If the requested size is smaller than the current size, and the + * current block is dynamically allocated, just return the old + * block. + */ + kReuse_OnShrink, + }; - SkAutoMalloc(size_t size, unsigned flags) - : SkAutoFree(sk_malloc_flags(size, flags)) {} - SkAutoMalloc() {} + /** + * Reallocates the block to a new size. The ptr may or may not change. + */ + void* reset(size_t size, OnShrink shrink = kAlloc_OnShrink) { + if (size == fSize || (kReuse_OnShrink == shrink && size < fSize)) { + return fPtr; + } + + sk_free(fPtr); + fPtr = size ? sk_malloc_throw(size) : NULL; + fSize = size; + + return fPtr; + } + + /** + * Releases the block back to the heap + */ + void free() { + this->reset(0); + } + + /** + * Return the allocated block. + */ + void* get() { return fPtr; } + const void* get() const { return fPtr; } - void* alloc(size_t size, - unsigned flags = (SK_MALLOC_THROW | SK_MALLOC_TEMP)) { - sk_free(set(sk_malloc_flags(size, flags))); - return get(); + /** Transfer ownership of the current ptr to the caller, setting the + internal reference to null. Note the caller is reponsible for calling + sk_free on the returned address. + */ + void* detach() { + void* ptr = fPtr; + fPtr = NULL; + fSize = 0; + return ptr; } + +private: + void* fPtr; + size_t fSize; // can be larger than the requested size (see kReuse) }; /** @@ -420,11 +495,12 @@ template <size_t kSize> class SkAutoSMalloc : SkNoncopyable { public: /** * Creates initially empty storage. get() returns a ptr, but it is to - * a zero-byte allocation. Must call realloc(size) to return an allocated + * a zero-byte allocation. Must call reset(size) to return an allocated * block. */ SkAutoSMalloc() { fPtr = fStorage; + fSize = 0; } /** @@ -434,7 +510,8 @@ public: */ explicit SkAutoSMalloc(size_t size) { fPtr = fStorage; - this->realloc(size); + fSize = 0; + this->reset(size); } /** @@ -461,7 +538,13 @@ public: * then the return block may be allocated locally, rather than from the * heap. */ - void* realloc(size_t size) { + void* reset(size_t size, + SkAutoMalloc::OnShrink shrink = SkAutoMalloc::kAlloc_OnShrink) { + if (size == fSize || (SkAutoMalloc::kReuse_OnShrink == shrink && + size < fSize)) { + return fPtr; + } + if (fPtr != (void*)fStorage) { sk_free(fPtr); } @@ -476,13 +559,10 @@ public: private: void* fPtr; + size_t fSize; // can be larger than the requested size (see kReuse) uint32_t fStorage[(kSize + 3) >> 2]; - // illegal - SkAutoSMalloc(const SkAutoSMalloc&); - SkAutoSMalloc& operator=(const SkAutoSMalloc&); }; #endif /* C++ */ #endif - diff --git a/include/core/SkUnPreMultiply.h b/include/core/SkUnPreMultiply.h index 44ea50e..7088918 100644 --- a/include/core/SkUnPreMultiply.h +++ b/include/core/SkUnPreMultiply.h @@ -1,22 +1,15 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkUnPreMultiply_DEFINED #define SkUnPreMultiply_DEFINED diff --git a/include/core/SkUnitMapper.h b/include/core/SkUnitMapper.h index 5d1ea35..2bd482b 100644 --- a/include/core/SkUnitMapper.h +++ b/include/core/SkUnitMapper.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkUnitMapper_DEFINED #define SkUnitMapper_DEFINED diff --git a/include/core/SkUserConfig.h b/include/core/SkUserConfig.h index 29e64f2..b409e82 100644 --- a/include/core/SkUserConfig.h +++ b/include/core/SkUserConfig.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkUserConfig_DEFINED #define SkUserConfig_DEFINED @@ -53,11 +46,6 @@ #include <utils/misc.h> #endif -#ifdef SK_BUILD_FOR_MAC - #undef SK_BUILD_FOR_MAC -#endif -#define SK_BUILD_FOR_UNIX - /* Scalars (the fractional value type in skia) can be implemented either as floats or 16.16 integers (fixed). Exactly one of these two symbols must be defined. @@ -68,7 +56,7 @@ /* Somewhat independent of how SkScalar is implemented, Skia also wants to know if it can use floats at all. Naturally, if SK_SCALAR_IS_FLOAT is defined, - then so muse SK_CAN_USE_FLOAT, but if scalars are fixed, SK_CAN_USE_FLOAT + SK_CAN_USE_FLOAT must be too; but if scalars are fixed, SK_CAN_USE_FLOAT can go either way. */ #define SK_CAN_USE_FLOAT @@ -119,25 +107,22 @@ #define SkLONGLONG int64_t -/* Some envorinments do not suport writable globals (eek!). If yours does not, - define this flag. - */ -//#define SK_USE_RUNTIME_GLOBALS - - /* To write debug messages to a console, skia will call SkDebugf(...) following printf conventions (e.g. const char* format, ...). If you want to redirect this to something other than printf, define yours here */ -#define SkDebugf(...) Android_SkDebugf(__FILE__, __LINE__, \ - __FUNCTION__, __VA_ARGS__) -void Android_SkDebugf(const char* file, int line, - const char* function, const char* format, ...); +//#define SkDebugf(...) MyFunction(__VA_ARGS__) -/* To enable additional blitters (and fontscaler code) to support separate - alpha channels for R G B channels, define SK_SUPPORT_LCDTEXT +/* + * To specify a different default font cache limit, define this. If this is + * undefined, skia will use a built-in value. */ -//#define SK_SUPPORT_LCDTEXT +//#define SK_DEFAULT_FONT_CACHE_LIMIT (1024 * 1024) + +/* If defined, use CoreText instead of ATSUI on OS X. +*/ +//#define SK_USE_MAC_CORE_TEXT + /* If zlib is available and you want to support the flate compression algorithm (used in PDF generation), define SK_ZLIB_INCLUDE to be the @@ -150,11 +135,22 @@ void Android_SkDebugf(const char* file, int line, */ //#define SK_ALLOW_LARGE_PDF_SCALARS +/* Define this to provide font subsetter in PDF generation. + */ +//#define SK_SFNTLY_SUBSETTER "sfntly/subsetter/font_subsetter.h" + /* Define this to remove dimension checks on bitmaps. Not all blits will be correct yet, so this is mostly for debugging the implementation. */ //#define SK_ALLOW_OVER_32K_BITMAPS +/* Define this to set the upper limit for text to support LCD. Values that + are very large increase the cost in the font cache and draw slower, without + improving readability. If this is undefined, Skia will use its default + value (e.g. 48) + */ +//#define SK_MAX_SIZE_FOR_LCDTEXT 48 + /* If SK_DEBUG is defined, then you can optionally define SK_SUPPORT_UNITTEST which will run additional self-tests at startup. These can take a long time, so this flag is optional. @@ -163,6 +159,18 @@ void Android_SkDebugf(const char* file, int line, #define SK_SUPPORT_UNITTEST #endif +/* If your system embeds skia and has complex event logging, define this + symbol to name a file that maps the following macros to your system's + equivalents: + SK_TRACE_EVENT0(event) + SK_TRACE_EVENT1(event, name1, value1) + SK_TRACE_EVENT2(event, name1, value1, name2, value2) + src/utils/SkDebugTrace.h has a trivial implementation that writes to + the debug output stream. If SK_USER_TRACE_INCLUDE_FILE is not defined, + SkTrace.h will define the above three macros to do nothing. +*/ +//#undef SK_USER_TRACE_INCLUDE_FILE + /* Change the ordering to work in X windows. */ #ifdef SK_SAMPLES_FOR_X @@ -173,4 +181,3 @@ void Android_SkDebugf(const char* file, int line, #endif #endif - diff --git a/include/core/SkUtils.h b/include/core/SkUtils.h index a346d48..b700b96 100644 --- a/include/core/SkUtils.h +++ b/include/core/SkUtils.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkUtils_DEFINED #define SkUtils_DEFINED @@ -39,13 +32,6 @@ void sk_memset32_portable(uint32_t dst[], uint32_t value, int count); typedef void (*SkMemset32Proc)(uint32_t dst[], uint32_t value, int count); SkMemset32Proc SkMemset32GetPlatformProc(); -#if defined(ANDROID) && !defined(SK_BUILD_FOR_ANDROID_NDK) - #include "cutils/memory.h" - - #define sk_memset16(dst, value, count) android_memset16(dst, value, (count) << 1) - #define sk_memset32(dst, value, count) android_memset32(dst, value, (count) << 2) -#endif - #ifndef sk_memset16 extern SkMemset16Proc sk_memset16; #endif @@ -98,6 +84,21 @@ size_t SkUTF16_FromUnichar(SkUnichar uni, uint16_t utf16[] = NULL); size_t SkUTF16_ToUTF8(const uint16_t utf16[], int numberOf16BitValues, char utf8[] = NULL); +inline bool SkUnichar_IsVariationSelector(SkUnichar uni) { +/* The 'true' ranges are: + * 0x180B <= uni <= 0x180D + * 0xFE00 <= uni <= 0xFE0F + * 0xE0100 <= uni <= 0xE01EF + */ + if (uni < 0x180B || uni > 0xE01EF) { + return false; + } + if ((uni > 0x180D && uni < 0xFE00) || (uni > 0xFE0F && uni < 0xE0100)) { + return false; + } + return true; +} + /////////////////////////////////////////////////////////////////////////////// class SkAutoTrace { diff --git a/include/core/SkWriter32.h b/include/core/SkWriter32.h index c8ebb6a..d7159ff 100644 --- a/include/core/SkWriter32.h +++ b/include/core/SkWriter32.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkWriter32_DEFINED #define SkWriter32_DEFINED @@ -28,11 +21,13 @@ class SkWStream; class SkWriter32 : SkNoncopyable { public: - SkWriter32(size_t minSize) { - fMinSize = minSize; - fSize = 0; - fHead = fTail = NULL; - fSingleBlock = NULL; + SkWriter32(size_t minSize) + : fMinSize(minSize), + fSize(0), + fSingleBlock(NULL), + fSingleBlockSize(0), + fHead(NULL), + fTail(NULL) { } ~SkWriter32(); diff --git a/include/core/SkXfermode.h b/include/core/SkXfermode.h index 6ab9d6d..0d1c207 100644 --- a/include/core/SkXfermode.h +++ b/include/core/SkXfermode.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkXfermode_DEFINED #define SkXfermode_DEFINED @@ -138,6 +131,18 @@ public: */ static bool AsMode(SkXfermode*, Mode* mode); + /** + * Returns true if the xfermode claims to be the specified Mode. This works + * correctly even if the xfermode is NULL (which equates to kSrcOver.) Thus + * you can say this without checking for a null... + * + * If (SkXfermode::IsMode(paint.getXfermode(), + * SkXfermode::kDstOver_Mode)) { + * ... + * } + */ + static bool IsMode(SkXfermode* xfer, Mode mode); + /** Return an SkXfermode object for the specified mode. */ static SkXfermode* Create(Mode mode); @@ -167,6 +172,7 @@ public: return AsMode(xfer, mode); } + SK_DECLARE_FLATTENABLE_REGISTRAR() protected: SkXfermode(SkFlattenableReadBuffer& rb) : SkFlattenable(rb) {} @@ -200,21 +206,26 @@ public: // overrides from SkXfermode virtual void xfer32(SkPMColor dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; virtual void xfer16(uint16_t dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; virtual void xfer4444(uint16_t dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; virtual void xferA8(SkAlpha dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; // overrides from SkFlattenable - virtual Factory getFactory() { return CreateProc; } - virtual void flatten(SkFlattenableWriteBuffer&); + virtual Factory getFactory() SK_OVERRIDE { return CreateProc; } + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; protected: SkProcXfermode(SkFlattenableReadBuffer&); + // allow subclasses to update this after we unflatten + void setProc(SkXfermodeProc proc) { + fProc = proc; + } + private: SkXfermodeProc fProc; diff --git a/include/effects/Sk1DPathEffect.h b/include/effects/Sk1DPathEffect.h index db01055..814e547 100644 --- a/include/effects/Sk1DPathEffect.h +++ b/include/effects/Sk1DPathEffect.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef Sk1DPathEffect_DEFINED #define Sk1DPathEffect_DEFINED @@ -64,27 +57,29 @@ public: SkPath1DPathEffect(const SkPath& path, SkScalar advance, SkScalar phase, Style); // override from SkPathEffect - virtual bool filterPath(SkPath* dst, const SkPath& src, SkScalar* width); + virtual bool filterPath(SkPath*, const SkPath&, SkScalar* width) SK_OVERRIDE; + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { + return SkNEW_ARGS(SkPath1DPathEffect, (buffer)); + } + + SK_DECLARE_FLATTENABLE_REGISTRAR() protected: SkPath1DPathEffect(SkFlattenableReadBuffer& buffer); // overrides from Sk1DPathEffect - virtual SkScalar begin(SkScalar contourLength); - virtual SkScalar next(SkPath* dst, SkScalar distance, SkPathMeasure&); + virtual SkScalar begin(SkScalar contourLength) SK_OVERRIDE; + virtual SkScalar next(SkPath*, SkScalar distance, SkPathMeasure&) SK_OVERRIDE; // overrides from SkFlattenable - virtual void flatten(SkFlattenableWriteBuffer& ); - virtual Factory getFactory() { return CreateProc; } + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE { return CreateProc; } private: SkPath fPath; // copied from constructor SkScalar fAdvance; // copied from constructor SkScalar fInitialOffset; // computed from phase Style fStyle; // copied from constructor - - static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { - return SkNEW_ARGS(SkPath1DPathEffect, (buffer)); - } typedef Sk1DPathEffect INHERITED; }; diff --git a/include/effects/Sk2DPathEffect.h b/include/effects/Sk2DPathEffect.h index 02ec760..b5d7fbb 100644 --- a/include/effects/Sk2DPathEffect.h +++ b/include/effects/Sk2DPathEffect.h @@ -1,40 +1,29 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef Sk2DPathEffect_DEFINED #define Sk2DPathEffect_DEFINED +#include "SkPath.h" #include "SkPathEffect.h" #include "SkMatrix.h" -// This class is not exported to java. class Sk2DPathEffect : public SkPathEffect { public: Sk2DPathEffect(const SkMatrix& mat); // overrides - // This method is not exported to java. - virtual bool filterPath(SkPath* dst, const SkPath& src, SkScalar* width); + virtual bool filterPath(SkPath*, const SkPath&, SkScalar* width) SK_OVERRIDE; // overrides from SkFlattenable - // This method is not exported to java. - virtual void flatten(SkFlattenableWriteBuffer&); - - // This method is not exported to java. - virtual Factory getFactory(); + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; protected: /** New virtual, to be overridden by subclasses. @@ -58,6 +47,8 @@ protected: // protected so that subclasses can call this during unflattening Sk2DPathEffect(SkFlattenableReadBuffer&); + SK_DECLARE_FLATTENABLE_REGISTRAR() + private: SkMatrix fMatrix, fInverse; // illegal @@ -70,4 +61,30 @@ private: typedef SkPathEffect INHERITED; }; +class SkPath2DPathEffect : public Sk2DPathEffect { +public: + /** + * Stamp the specified path to fill the shape, using the matrix to define + * the latice. + */ + SkPath2DPathEffect(const SkMatrix&, const SkPath&); + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + + SK_DECLARE_FLATTENABLE_REGISTRAR() + +protected: + SkPath2DPathEffect(SkFlattenableReadBuffer& buffer); + + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; + virtual void next(const SkPoint&, int u, int v, SkPath* dst) SK_OVERRIDE; + +private: + SkPath fPath; + + typedef Sk2DPathEffect INHERITED; +}; + + #endif diff --git a/include/effects/SkArithmeticMode.h b/include/effects/SkArithmeticMode.h new file mode 100644 index 0000000..70d660f --- /dev/null +++ b/include/effects/SkArithmeticMode.h @@ -0,0 +1,30 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkArithmeticMode_DEFINED +#define SkArithmeticMode_DEFINED + +#include "SkXfermode.h" + +class SkArithmeticMode : public SkXfermode { +public: + /** + * result = clamp[k1 * src * dst + k2 * src + k3 * dst + k4] + * + * src and dst are treated as being [0.0 .. 1.0]. The polynomial is + * evaluated on their unpremultiplied components. + * + * k1=k2=k3=0, k4=1.0 results in returning opaque white + * k1=k3=k4=0, k2=1.0 results in returning the src + * k1=k2=k4=0, k3=1.0 results in returning the dst + */ + static SkXfermode* Create(SkScalar k1, SkScalar k2, + SkScalar k3, SkScalar k4); +}; + +#endif + diff --git a/include/effects/SkAvoidXfermode.h b/include/effects/SkAvoidXfermode.h index b52e6f5..398eaea 100644 --- a/include/effects/SkAvoidXfermode.h +++ b/include/effects/SkAvoidXfermode.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkAvoidXfermode_DEFINED #define SkAvoidXfermode_DEFINED @@ -50,22 +43,24 @@ public: // overrides from SkXfermode virtual void xfer32(SkPMColor dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; virtual void xfer16(uint16_t dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; virtual void xfer4444(uint16_t dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; virtual void xferA8(SkAlpha dst[], const SkPMColor src[], int count, - const SkAlpha aa[]); + const SkAlpha aa[]) SK_OVERRIDE; // overrides from SkFlattenable - virtual Factory getFactory(); - virtual void flatten(SkFlattenableWriteBuffer&); + virtual Factory getFactory() SK_OVERRIDE; + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(SkAvoidXfermode, (buffer)); } + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkAvoidXfermode(SkFlattenableReadBuffer&); diff --git a/include/effects/SkBlurDrawLooper.h b/include/effects/SkBlurDrawLooper.h index 846048c..be1a78e 100644 --- a/include/effects/SkBlurDrawLooper.h +++ b/include/effects/SkBlurDrawLooper.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBlurDrawLooper_DEFINED #define SkBlurDrawLooper_DEFINED @@ -55,6 +48,7 @@ public: return SkNEW_ARGS(SkBlurDrawLooper, (buffer)); } + SK_DECLARE_FLATTENABLE_REGISTRAR() protected: SkBlurDrawLooper(SkFlattenableReadBuffer&); diff --git a/include/effects/SkBlurImageFilter.h b/include/effects/SkBlurImageFilter.h new file mode 100644 index 0000000..4c9798b --- /dev/null +++ b/include/effects/SkBlurImageFilter.h @@ -0,0 +1,40 @@ +/* + * Copyright 2011 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef SkBlurImageFilter_DEFINED +#define SkBlurImageFilter_DEFINED + +#include "SkImageFilter.h" + +class SK_API SkBlurImageFilter : public SkImageFilter { +public: + SkBlurImageFilter(SkScalar sigmaX, SkScalar sigmaY); + + virtual bool asABlur(SkSize* sigma) const SK_OVERRIDE; + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { + return SkNEW_ARGS(SkBlurImageFilter, (buffer)); + } + + SK_DECLARE_FLATTENABLE_REGISTRAR() + +protected: + explicit SkBlurImageFilter(SkFlattenableReadBuffer& buffer); + + virtual bool onFilterImage(Proxy*, const SkBitmap& src, const SkMatrix&, + SkBitmap* result, SkIPoint* offset) SK_OVERRIDE; + virtual void flatten(SkFlattenableWriteBuffer& buffer) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE { return CreateProc; } + +private: + SkSize fSigma; + typedef SkImageFilter INHERITED; +}; + +#endif + diff --git a/include/effects/SkBlurMaskFilter.h b/include/effects/SkBlurMaskFilter.h index daca68d..9e85d87 100644 --- a/include/effects/SkBlurMaskFilter.h +++ b/include/effects/SkBlurMaskFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBlurMaskFilter_DEFINED #define SkBlurMaskFilter_DEFINED @@ -62,6 +55,8 @@ public: SkScalar ambient, SkScalar specular, SkScalar blurRadius); + SK_DECLARE_FLATTENABLE_REGISTRAR() + private: SkBlurMaskFilter(); // can't be instantiated }; diff --git a/include/effects/SkColorMatrix.h b/include/effects/SkColorMatrix.h index cee5d6e..ee383db 100644 --- a/include/effects/SkColorMatrix.h +++ b/include/effects/SkColorMatrix.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2007 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkColorMatrix_DEFINED #define SkColorMatrix_DEFINED diff --git a/include/effects/SkColorMatrixFilter.h b/include/effects/SkColorMatrixFilter.h index d8ef81c..1475258 100644 --- a/include/effects/SkColorMatrixFilter.h +++ b/include/effects/SkColorMatrixFilter.h @@ -1,26 +1,19 @@ + /* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2007 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkColorMatrixFilter_DEFINED #define SkColorMatrixFilter_DEFINED #include "SkColorFilter.h" #include "SkColorMatrix.h" -class SkColorMatrixFilter : public SkColorFilter { +class SK_API SkColorMatrixFilter : public SkColorFilter { public: SkColorMatrixFilter(); explicit SkColorMatrixFilter(const SkColorMatrix&); @@ -30,12 +23,13 @@ public: void setArray(const SkScalar array[20]); // overrides from SkColorFilter - virtual void filterSpan(const SkPMColor src[], int count, SkPMColor[]); - virtual void filterSpan16(const uint16_t src[], int count, uint16_t[]); - virtual uint32_t getFlags(); + virtual void filterSpan(const SkPMColor src[], int count, SkPMColor[]) SK_OVERRIDE; + virtual void filterSpan16(const uint16_t src[], int count, uint16_t[]) SK_OVERRIDE; + virtual uint32_t getFlags() SK_OVERRIDE; + virtual bool asColorMatrix(SkScalar matrix[20]) SK_OVERRIDE; // overrides for SkFlattenable - virtual void flatten(SkFlattenableWriteBuffer& buffer); + virtual void flatten(SkFlattenableWriteBuffer& buffer) SK_OVERRIDE; struct State { int32_t fArray[20]; @@ -45,6 +39,8 @@ public: static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer); + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: // overrides for SkFlattenable virtual Factory getFactory(); diff --git a/include/effects/SkCornerPathEffect.h b/include/effects/SkCornerPathEffect.h index 823de3f..990bad0 100644 --- a/include/effects/SkCornerPathEffect.h +++ b/include/effects/SkCornerPathEffect.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkCornerPathEffect_DEFINED #define SkCornerPathEffect_DEFINED @@ -42,17 +35,15 @@ public: // This method is not exported to java. virtual void flatten(SkFlattenableWriteBuffer&); + static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkCornerPathEffect(SkFlattenableReadBuffer&); private: SkScalar fRadius; - - static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); - - // illegal - SkCornerPathEffect(const SkCornerPathEffect&); - SkCornerPathEffect& operator=(const SkCornerPathEffect&); typedef SkPathEffect INHERITED; }; diff --git a/include/effects/SkDashPathEffect.h b/include/effects/SkDashPathEffect.h index 145f67d..6d34910 100644 --- a/include/effects/SkDashPathEffect.h +++ b/include/effects/SkDashPathEffect.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDashPathEffect_DEFINED #define SkDashPathEffect_DEFINED @@ -44,6 +37,10 @@ public: // This method is not exported to java. virtual void flatten(SkFlattenableWriteBuffer&); + static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkDashPathEffect(SkFlattenableReadBuffer&); @@ -56,8 +53,6 @@ private: SkScalar fIntervalLength; bool fScaleToFit; - static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); - typedef SkPathEffect INHERITED; }; diff --git a/include/effects/SkDiscretePathEffect.h b/include/effects/SkDiscretePathEffect.h index 2950950..5369ddb 100644 --- a/include/effects/SkDiscretePathEffect.h +++ b/include/effects/SkDiscretePathEffect.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDiscretePathEffect_DEFINED #define SkDiscretePathEffect_DEFINED @@ -41,13 +34,15 @@ public: // This method is not exported to java. virtual void flatten(SkFlattenableWriteBuffer&); + static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkDiscretePathEffect(SkFlattenableReadBuffer&); private: SkScalar fSegLength, fPerterb; - - static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); typedef SkPathEffect INHERITED; }; diff --git a/include/effects/SkDrawExtraPathEffect.h b/include/effects/SkDrawExtraPathEffect.h index 65e255a..c7611f0 100644 --- a/include/effects/SkDrawExtraPathEffect.h +++ b/include/effects/SkDrawExtraPathEffect.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SK_DRAW_EXTRA_PATH_EFFECT_H #define SK_DRAW_EXTRA_PATH_EFFECT_H class SkAnimator; diff --git a/include/effects/SkEffects.h b/include/effects/SkEffects.h new file mode 100644 index 0000000..04091de --- /dev/null +++ b/include/effects/SkEffects.h @@ -0,0 +1,16 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkEffects_DEFINED +#define SkEffects_DEFINED + +class SkEffects { +public: + static void Init(); +}; + +#endif diff --git a/include/effects/SkEmbossMaskFilter.h b/include/effects/SkEmbossMaskFilter.h index b0c12c5..257e19a 100644 --- a/include/effects/SkEmbossMaskFilter.h +++ b/include/effects/SkEmbossMaskFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkEmbossMaskFilter_DEFINED #define SkEmbossMaskFilter_DEFINED @@ -48,6 +41,8 @@ public: // This method is not exported to java. virtual void flatten(SkFlattenableWriteBuffer&); + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkEmbossMaskFilter(SkFlattenableReadBuffer&); diff --git a/include/effects/SkGradientShader.h b/include/effects/SkGradientShader.h index 5623be4..3232703 100644 --- a/include/effects/SkGradientShader.h +++ b/include/effects/SkGradientShader.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkGradientShader_DEFINED #define SkGradientShader_DEFINED @@ -119,6 +112,8 @@ public: static SkShader* CreateSweep(SkScalar cx, SkScalar cy, const SkColor colors[], const SkScalar pos[], int count, SkUnitMapper* mapper = NULL); + + SK_DECLARE_FLATTENABLE_REGISTRAR() }; #endif diff --git a/include/effects/SkGroupShape.h b/include/effects/SkGroupShape.h index 2c851fa..7764003 100644 --- a/include/effects/SkGroupShape.h +++ b/include/effects/SkGroupShape.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkGroupShape_DEFINED #define SkGroupShape_DEFINED @@ -131,6 +138,8 @@ public: // public for Registrar static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: // overrides virtual void onDraw(SkCanvas*); diff --git a/include/effects/SkKernel33MaskFilter.h b/include/effects/SkKernel33MaskFilter.h index 45aaef8..2b9e6d4 100644 --- a/include/effects/SkKernel33MaskFilter.h +++ b/include/effects/SkKernel33MaskFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkKernel33MaskFilter_DEFINED #define SkKernel33MaskFilter_DEFINED diff --git a/include/effects/SkLayerDrawLooper.h b/include/effects/SkLayerDrawLooper.h index 8627ae4..697d7b2 100644 --- a/include/effects/SkLayerDrawLooper.h +++ b/include/effects/SkLayerDrawLooper.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkLayerDrawLooper_DEFINED #define SkLayerDrawLooper_DEFINED @@ -15,7 +22,8 @@ public: * Bits specifies which aspects of the layer's paint should replace the * corresponding aspects on the draw's paint. * kEntirePaint_Bits means use the layer's paint completely. - * 0 means ignore the layer's paint. + * 0 means ignore the layer's paint... except that LayerInfo's fFlagsMask + * and fColorMode are always applied. */ enum Bits { kStyle_Bit = 1 << 0, //!< use this layer's Style/stroke settings @@ -26,7 +34,15 @@ public: kColorFilter_Bit = 1 << 5, //!< use this layer's colorfilter kXfermode_Bit = 1 << 6, //!< use this layer's xfermode - kEntirePaint_Bits = -1, //!< use this layer's paint entirely + /** + * Use the layer's paint entirely, with these exceptions: + * - We never override the draw's paint's text_encoding, since that is + * used to interpret the text/len parameters in draw[Pos]Text. + * - Flags and Color are always computed using the LayerInfo's + * fFlagsMask and fColorMode. + */ + kEntirePaint_Bits = -1, + }; typedef int32_t BitFlags; @@ -90,6 +106,8 @@ public: return SkNEW_ARGS(SkLayerDrawLooper, (buffer)); } + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkLayerDrawLooper(SkFlattenableReadBuffer&); diff --git a/include/effects/SkLayerRasterizer.h b/include/effects/SkLayerRasterizer.h index 0373b05..91deb61 100644 --- a/include/effects/SkLayerRasterizer.h +++ b/include/effects/SkLayerRasterizer.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkLayerRasterizer_DEFINED #define SkLayerRasterizer_DEFINED @@ -43,6 +36,10 @@ public: virtual Factory getFactory(); virtual void flatten(SkFlattenableWriteBuffer&); + static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkLayerRasterizer(SkFlattenableReadBuffer&); @@ -53,8 +50,6 @@ protected: private: SkDeque fLayers; - - static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); typedef SkRasterizer INHERITED; }; diff --git a/include/effects/SkPaintFlagsDrawFilter.h b/include/effects/SkPaintFlagsDrawFilter.h index e4ec466..66a43cc 100644 --- a/include/effects/SkPaintFlagsDrawFilter.h +++ b/include/effects/SkPaintFlagsDrawFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPaintFlagsDrawFilter_DEFINED #define SkPaintFlagsDrawFilter_DEFINED diff --git a/include/effects/SkPixelXorXfermode.h b/include/effects/SkPixelXorXfermode.h index 1957c9e..a7197ab 100644 --- a/include/effects/SkPixelXorXfermode.h +++ b/include/effects/SkPixelXorXfermode.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2007 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPixelXorXfermode_DEFINED #define SkPixelXorXfermode_DEFINED @@ -36,6 +29,8 @@ public: return SkNEW_ARGS(SkPixelXorXfermode, (buffer)); } + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: // override from SkXfermode virtual SkPMColor xferColor(SkPMColor src, SkPMColor dst); diff --git a/include/effects/SkPorterDuff.h b/include/effects/SkPorterDuff.h index 54f81ea..44d94f8 100644 --- a/include/effects/SkPorterDuff.h +++ b/include/effects/SkPorterDuff.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPorterDuff_DEFINED #define SkPorterDuff_DEFINED @@ -52,7 +45,7 @@ public: kMultiply_Mode, //!< [Sa * Da, Sc * Dc] kScreen_Mode, //!< [Sa + Da - Sa * Da, Sc + Dc - Sc * Dc] kAdd_Mode, //!< Saturate(S + D) -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID kOverlay_Mode, #endif diff --git a/include/effects/SkRectShape.h b/include/effects/SkRectShape.h index 9b8cfc1..519398c 100644 --- a/include/effects/SkRectShape.h +++ b/include/effects/SkRectShape.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkRectShape_DEFINED #define SkRectShape_DEFINED @@ -40,6 +47,8 @@ public: // public for Registrar static SkFlattenable* CreateProc(SkFlattenableReadBuffer&); + SK_DECLARE_FLATTENABLE_REGISTRAR() + protected: SkRectShape(SkFlattenableReadBuffer&); diff --git a/include/effects/SkTableColorFilter.h b/include/effects/SkTableColorFilter.h new file mode 100644 index 0000000..0aefdbd --- /dev/null +++ b/include/effects/SkTableColorFilter.h @@ -0,0 +1,34 @@ + +#ifndef SkTableColorFilter_DEFINED +#define SkTableColorFilter_DEFINED + +#include "SkColorFilter.h" + +class SkTableColorFilter { +public: + /** + * Create a table colorfilter, copying the table into the filter, and + * applying it to all 4 components. + * a' = table[a]; + * r' = table[r]; + * g' = table[g]; + * b' = table[b]; + * Compoents are operated on in unpremultiplied space. If the incomming + * colors are premultiplied, they are temporarily unpremultiplied, then + * the table is applied, and then the result is remultiplied. + */ + static SkColorFilter* Create(const uint8_t table[256]); + + /** + * Create a table colorfilter, with a different table for each + * component [A, R, G, B]. If a given table is NULL, then it is + * treated as identity, with the component left unchanged. If a table + * is not null, then its contents are copied into the filter. + */ + static SkColorFilter* CreateARGB(const uint8_t tableA[256], + const uint8_t tableR[256], + const uint8_t tableG[256], + const uint8_t tableB[256]); +}; + +#endif diff --git a/include/effects/SkTableMaskFilter.h b/include/effects/SkTableMaskFilter.h index a57053d..f213de7 100644 --- a/include/effects/SkTableMaskFilter.h +++ b/include/effects/SkTableMaskFilter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTableMaskFilter_DEFINED #define SkTableMaskFilter_DEFINED diff --git a/include/effects/SkTestImageFilters.h b/include/effects/SkTestImageFilters.h new file mode 100755 index 0000000..db020ad --- /dev/null +++ b/include/effects/SkTestImageFilters.h @@ -0,0 +1,157 @@ + +#ifndef _SkTestImageFilters_h +#define _SkTestImageFilters_h + +#include "SkImageFilter.h" + +class SkOffsetImageFilter : public SkImageFilter { +public: + SkOffsetImageFilter(SkScalar dx, SkScalar dy) { + fOffset.set(dx, dy); + } + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { + return SkNEW_ARGS(SkOffsetImageFilter, (buffer)); + } + +protected: + SkOffsetImageFilter(SkFlattenableReadBuffer& buffer); + + virtual bool onFilterImage(Proxy*, const SkBitmap& src, const SkMatrix&, + SkBitmap* result, SkIPoint* loc) SK_OVERRIDE; + virtual bool onFilterBounds(const SkIRect&, const SkMatrix&, SkIRect*) SK_OVERRIDE; + // overrides from SkFlattenable + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; + +private: + SkVector fOffset; + + typedef SkImageFilter INHERITED; +}; + +class SkComposeImageFilter : public SkImageFilter { +public: + SkComposeImageFilter(SkImageFilter* outer, SkImageFilter* inner) { + fOuter = outer; + fInner = inner; + SkSafeRef(outer); + SkSafeRef(inner); + } + virtual ~SkComposeImageFilter(); + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { + return SkNEW_ARGS(SkComposeImageFilter, (buffer)); + } + +protected: + SkComposeImageFilter(SkFlattenableReadBuffer& buffer); + + virtual bool onFilterImage(Proxy*, const SkBitmap& src, const SkMatrix&, + SkBitmap* result, SkIPoint* loc) SK_OVERRIDE; + virtual bool onFilterBounds(const SkIRect&, const SkMatrix&, SkIRect*) SK_OVERRIDE; + // overrides from SkFlattenable + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; + +private: + SkImageFilter* fOuter; + SkImageFilter* fInner; + + typedef SkImageFilter INHERITED; +}; + +#include "SkXfermode.h" + +class SkMergeImageFilter : public SkImageFilter { +public: + SkMergeImageFilter(SkImageFilter* first, SkImageFilter* second, + SkXfermode::Mode = SkXfermode::kSrcOver_Mode); + SkMergeImageFilter(SkImageFilter* const filters[], int count, + const SkXfermode::Mode modes[] = NULL); + virtual ~SkMergeImageFilter(); + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { + return SkNEW_ARGS(SkMergeImageFilter, (buffer)); + } + +protected: + SkMergeImageFilter(SkFlattenableReadBuffer& buffer); + + virtual bool onFilterImage(Proxy*, const SkBitmap& src, const SkMatrix&, + SkBitmap* result, SkIPoint* loc) SK_OVERRIDE; + virtual bool onFilterBounds(const SkIRect&, const SkMatrix&, SkIRect*) SK_OVERRIDE; + // overrides from SkFlattenable + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; + +private: + SkImageFilter** fFilters; + uint8_t* fModes; // SkXfermode::Mode + int fCount; + + // private storage, to avoid dynamically allocating storage for our copy + // of the filters and modes (unless fCount is so large we can't fit). + intptr_t fStorage[16]; + + void initAlloc(int count, bool hasModes); + void init(SkImageFilter* const [], int count, const SkXfermode::Mode []); + + typedef SkImageFilter INHERITED; +}; + +class SkColorFilter; + +class SkColorFilterImageFilter : public SkImageFilter { +public: + SkColorFilterImageFilter(SkColorFilter* cf) : fColorFilter(cf) { + SkSafeRef(cf); + } + virtual ~SkColorFilterImageFilter(); + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { + return SkNEW_ARGS(SkColorFilterImageFilter, (buffer)); + } + +protected: + SkColorFilterImageFilter(SkFlattenableReadBuffer& buffer); + + virtual bool onFilterImage(Proxy*, const SkBitmap& src, const SkMatrix&, + SkBitmap* result, SkIPoint* loc) SK_OVERRIDE; + // overrides from SkFlattenable + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; + +private: + SkColorFilter* fColorFilter; + + typedef SkImageFilter INHERITED; +}; + +/////////////////////////////////////////////////////////////////////////////// + +// Fun mode that scales down (only) and then scales back up to look pixelated +class SkDownSampleImageFilter : public SkImageFilter { +public: + SkDownSampleImageFilter(SkScalar scale) : fScale(scale) {} + + static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) { + return SkNEW_ARGS(SkDownSampleImageFilter, (buffer)); + } + +protected: + SkDownSampleImageFilter(SkFlattenableReadBuffer& buffer); + + virtual bool onFilterImage(Proxy*, const SkBitmap& src, const SkMatrix&, + SkBitmap* result, SkIPoint* loc) SK_OVERRIDE; + // overrides from SkFlattenable + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + virtual Factory getFactory() SK_OVERRIDE; + +private: + SkScalar fScale; + + typedef SkImageFilter INHERITED; +}; + +#endif diff --git a/include/effects/SkTransparentShader.h b/include/effects/SkTransparentShader.h index 5e87609..e951bba 100644 --- a/include/effects/SkTransparentShader.h +++ b/include/effects/SkTransparentShader.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTransparentShader_DEFINED #define SkTransparentShader_DEFINED @@ -22,19 +15,18 @@ class SkTransparentShader : public SkShader { public: SkTransparentShader() {} - virtual uint32_t getFlags(); + + virtual uint32_t getFlags() SK_OVERRIDE; virtual bool setContext( const SkBitmap& device, const SkPaint& paint, - const SkMatrix& matrix); - virtual void shadeSpan(int x, int y, SkPMColor[], int count); - virtual void shadeSpan16(int x, int y, uint16_t span[], int count); + const SkMatrix& matrix) SK_OVERRIDE; + virtual void shadeSpan(int x, int y, SkPMColor[], int count) SK_OVERRIDE; + virtual void shadeSpan16(int x, int y, uint16_t span[], int count) SK_OVERRIDE; // overrides for SkFlattenable - virtual Factory getFactory() { return Create; } - virtual void flatten(SkFlattenableWriteBuffer& buffer) { - this->INHERITED::flatten(buffer); - } - + virtual Factory getFactory() SK_OVERRIDE; + virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE; + private: // these are a cache from the call to setContext() const SkBitmap* fDevice; diff --git a/include/gpu/GrClip.h b/include/gpu/GrClip.h new file mode 100644 index 0000000..d86eb97 --- /dev/null +++ b/include/gpu/GrClip.h @@ -0,0 +1,141 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrClip_DEFINED +#define GrClip_DEFINED + +#include "GrClipIterator.h" +#include "GrRect.h" +#include "GrPath.h" +#include "GrTemplates.h" + +#include "SkTArray.h" + +class GrClip { +public: + GrClip(); + GrClip(const GrClip& src); + /** + * If specified, the conservativeBounds parameter already takes (tx,ty) + * into account. + */ + GrClip(GrClipIterator* iter, GrScalar tx, GrScalar ty, + const GrRect* conservativeBounds = NULL); + GrClip(const GrIRect& rect); + GrClip(const GrRect& rect); + + ~GrClip(); + + GrClip& operator=(const GrClip& src); + + bool hasConservativeBounds() const { return fConservativeBoundsValid; } + + const GrRect& getConservativeBounds() const { return fConservativeBounds; } + + int getElementCount() const { return fList.count(); } + + GrClipType getElementType(int i) const { return fList[i].fType; } + + const GrPath& getPath(int i) const { + GrAssert(kPath_ClipType == fList[i].fType); + return fList[i].fPath; + } + + GrPathFill getPathFill(int i) const { + GrAssert(kPath_ClipType == fList[i].fType); + return fList[i].fPathFill; + } + + const GrRect& getRect(int i) const { + GrAssert(kRect_ClipType == fList[i].fType); + return fList[i].fRect; + } + + GrSetOp getOp(int i) const { return fList[i].fOp; } + + bool isRect() const { + if (1 == fList.count() && kRect_ClipType == fList[0].fType && + (kIntersect_SetOp == fList[0].fOp || + kReplace_SetOp == fList[0].fOp)) { + // if we determined that the clip is a single rect + // we ought to have also used that rect as the bounds. + GrAssert(fConservativeBoundsValid); + GrAssert(fConservativeBounds == fList[0].fRect); + return true; + } else { + return false; + } + } + + bool isEmpty() const { return 0 == fList.count(); } + + /** + * Resets this clip to be empty + */ + void setEmpty(); + + /** + * If specified, the bounds parameter already takes (tx,ty) into account. + */ + void setFromIterator(GrClipIterator* iter, GrScalar tx, GrScalar ty, + const GrRect* conservativeBounds = NULL); + void setFromRect(const GrRect& rect); + void setFromIRect(const GrIRect& rect); + + friend bool operator==(const GrClip& a, const GrClip& b) { + if (a.fList.count() != b.fList.count()) { + return false; + } + int count = a.fList.count(); + for (int i = 0; i < count; ++i) { + if (a.fList[i] != b.fList[i]) { + return false; + } + } + return true; + } + friend bool operator!=(const GrClip& a, const GrClip& b) { + return !(a == b); + } + +private: + struct Element { + GrClipType fType; + GrRect fRect; + GrPath fPath; + GrPathFill fPathFill; + GrSetOp fOp; + bool operator ==(const Element& e) const { + if (e.fType != fType || e.fOp != fOp) { + return false; + } + switch (fType) { + case kRect_ClipType: + return fRect == e.fRect; + case kPath_ClipType: + return fPath == e.fPath; + default: + GrCrash("Unknown clip element type."); + return false; // suppress warning + } + } + bool operator !=(const Element& e) const { return !(*this == e); } + }; + + GrRect fConservativeBounds; + bool fConservativeBoundsValid; + + enum { + kPreAllocElements = 4, + }; + SkSTArray<kPreAllocElements, Element> fList; +}; +#endif + diff --git a/include/gpu/GrClipIterator.h b/include/gpu/GrClipIterator.h new file mode 100644 index 0000000..4a5cc71 --- /dev/null +++ b/include/gpu/GrClipIterator.h @@ -0,0 +1,80 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrClipIterator_DEFINED +#define GrClipIterator_DEFINED + +#include "GrPath.h" +#include "GrRect.h" + +/** + * A clip is a list of paths and/or rects with set operations to combine them. + */ +class GrClipIterator { +public: + virtual ~GrClipIterator() {} + + /** + * Returns true if there are no more rects to process + */ + virtual bool isDone() const = 0; + + /** + * Rewind the iterator to replay the set of clip elements again + */ + virtual void rewind() = 0; + + /** + * Get the type of the current clip element + */ + virtual GrClipType getType() const = 0; + + /** + * Return the current path. It is an error to call this when isDone() is + * true or when getType() is kRect_Type. + */ + virtual const GrPath* getPath() = 0; + + /** + * Return the fill rule for the path. It is an error to call this when + * isDone() is true or when getType is kRect_Type. + */ + virtual GrPathFill getPathFill() const = 0; + + /** + * Return the current rect. It is an error to call this when isDone is true + * or when getType() is kPath_Type. + */ + virtual void getRect(GrRect* rect) const = 0; + + /** + * Gets the operation used to apply the current item to previously iterated + * items. Iterators should not produce a Replace op. + */ + virtual GrSetOp getOp() const = 0; + + /** + * Call to move to the next element in the list, previous path iter can be + * made invalid. + */ + virtual void next() = 0; +}; + +/** + * Call to rewind iter, first checking to see if iter is NULL + */ +static inline void GrSafeRewind(GrClipIterator* iter) { + if (iter) { + iter->rewind(); + } +} + +#endif + diff --git a/include/gpu/GrColor.h b/include/gpu/GrColor.h new file mode 100644 index 0000000..ed666de --- /dev/null +++ b/include/gpu/GrColor.h @@ -0,0 +1,62 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrColor_DEFINED +#define GrColor_DEFINED + +#include "GrTypes.h" + +/** + * GrColor is 4 bytes for R, G, B, A, in a compile-time specific order. The + * components are stored premultiplied. + */ +typedef uint32_t GrColor; + + +// shift amount to assign a component to a GrColor int +// These shift values are chosen for compatibility with GL attrib arrays +// ES doesn't allow BGRA vertex attrib order so if they were not in this order +// we'd have to swizzle in shaders. Note the assumption that the cpu is little +// endian. +#define GrColor_SHIFT_R 0 +#define GrColor_SHIFT_G 8 +#define GrColor_SHIFT_B 16 +#define GrColor_SHIFT_A 24 + +/** + * Pack 4 components (RGBA) into a GrColor int + */ +static inline GrColor GrColorPackRGBA(unsigned r, unsigned g, + unsigned b, unsigned a) { + GrAssert((uint8_t)r == r); + GrAssert((uint8_t)g == g); + GrAssert((uint8_t)b == b); + GrAssert((uint8_t)a == a); + return (r << GrColor_SHIFT_R) | + (g << GrColor_SHIFT_G) | + (b << GrColor_SHIFT_B) | + (a << GrColor_SHIFT_A); +} + +// extract a component (byte) from a GrColor int + +#define GrColorUnpackR(color) (((color) >> GrColor_SHIFT_R) & 0xFF) +#define GrColorUnpackG(color) (((color) >> GrColor_SHIFT_G) & 0xFF) +#define GrColorUnpackB(color) (((color) >> GrColor_SHIFT_B) & 0xFF) +#define GrColorUnpackA(color) (((color) >> GrColor_SHIFT_A) & 0xFF) + +/** + * Since premultiplied means that alpha >= color, we construct a color with + * each component==255 and alpha == 0 to be "illegal" + */ +#define GrColor_ILLEGAL (~(0xFF << GrColor_SHIFT_A)) + +#endif + diff --git a/include/gpu/GrConfig.h b/include/gpu/GrConfig.h new file mode 100644 index 0000000..72b9748 --- /dev/null +++ b/include/gpu/GrConfig.h @@ -0,0 +1,439 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrConfig_DEFINED +#define GrConfig_DEFINED + +/////////////////////////////////////////////////////////////////////////////// +// preconfig section: +// +// All the work before including GrUserConfig.h should center around guessing +// what platform we're on, and defining low-level symbols based on that. +// +// A build environment may have already defined symbols, so we first check +// for that +// + +// hack to ensure we know what sort of Apple platform we're on +#if defined(__APPLE_CPP__) || defined(__APPLE_CC__) + #include <TargetConditionals.h> +#endif + +/** + * Gr defines are set to 0 or 1, rather than being undefined or defined + */ + +#if !defined(GR_ANDROID_BUILD) + #define GR_ANDROID_BUILD 0 +#endif +#if !defined(GR_IOS_BUILD) + #define GR_IOS_BUILD 0 +#endif +#if !defined(GR_LINUX_BUILD) + #define GR_LINUX_BUILD 0 +#endif +#if !defined(GR_MAC_BUILD) + #define GR_MAC_BUILD 0 +#endif +#if !defined(GR_WIN32_BUILD) + #define GR_WIN32_BUILD 0 +#endif +#if !defined(GR_QNX_BUILD) + #define GR_QNX_BUILD 0 +#endif + +/** + * If no build target has been defined, attempt to infer. + */ +#if !GR_ANDROID_BUILD && !GR_IOS_BUILD && !GR_LINUX_BUILD && !GR_MAC_BUILD && !GR_WIN32_BUILD && !GR_QNX_BUILD + #if defined(_WIN32) + #undef GR_WIN32_BUILD + #define GR_WIN32_BUILD 1 +// #error "WIN" + #elif TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR + #undef GR_IOS_BUILD + #define GR_IOS_BUILD 1 +// #error "IOS" + #elif defined(SK_BUILD_FOR_ANDROID) + #undef GR_ANDROID_BUILD + #define GR_ANDROID_BUILD 1 +// #error "ANDROID" + #elif TARGET_OS_MAC + #undef GR_MAC_BUILD + #define GR_MAC_BUILD 1 +// #error "MAC" + #elif TARGET_OS_QNX || defined(__QNXNTO__) + #undef GR_QNX_BUILD + #define GR_QNX_BUILD 1 +// #error "QNX" + #else + #undef GR_LINUX_BUILD + #define GR_LINUX_BUILD 1 +// #error "LINUX" + #endif +#endif + +// we need both GR_DEBUG and GR_RELEASE to be defined as 0 or 1 +// +#ifndef GR_DEBUG + #ifdef GR_RELEASE + #define GR_DEBUG !GR_RELEASE + #else + #ifdef NDEBUG + #define GR_DEBUG 0 + #else + #define GR_DEBUG 1 + #endif + #endif +#endif + +#ifndef GR_RELEASE + #define GR_RELEASE !GR_DEBUG +#endif + +#if GR_DEBUG == GR_RELEASE + #error "GR_DEBUG and GR_RELEASE must not be the same" +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +#if GR_WIN32_BUILD +// VC8 doesn't support stdint.h, so we define those types here. +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef int int32_t; +typedef unsigned uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +/* + * Include stdint.h with defines that trigger declaration of C99 limit/const + * macros here before anyone else has a chance to include stdint.h without + * these. + */ +#define __STDC_LIMIT_MACROS +#define __STDC_CONSTANT_MACROS +#include <stdint.h> +#endif + +/* + * The "user config" file can be empty, and everything should work. It is + * meant to store a given platform/client's overrides of our guess-work. + * + * A alternate user config file can be specified by defining + * GR_USER_CONFIG_FILE. It should be defined relative to GrConfig.h + * + * e.g. it can specify GR_DEBUG/GR_RELEASE as it please, change the BUILD + * target, or supply its own defines for anything else (e.g. GR_SCALAR) + */ +#if !defined(GR_USER_CONFIG_FILE) + #include "GrUserConfig.h" +#else + #include GR_USER_CONFIG_FILE +#endif + + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +// postconfig section: +// + +// GR_IMPLEMENTATION should be define to 1 when building Gr and 0 when including +// it in another dependent build. The Gr makefile/ide-project should define this +// to 1. +#if !defined(GR_IMPLEMENTATION) + #define GR_IMPLEMENTATION 0 +#endif + +// If Gr is built as a shared library then GR_DLL should be defined to 1 (both +// when building Gr and when including its headers in dependent builds). Only +// currently supported minimally for Chrome's Win32 Multi-DLL build (TODO: +// correctly exort all of the public API correctly and support shared lib on +// other platforms). +#if !defined(GR_DLL) + #define GR_DLL 0 +#endif + +#if GR_DLL + #if GR_WIN32_BUILD + #if GR_IMPLEMENTATION + #define GR_API __declspec(dllexport) + #else + #define GR_API __declspec(dllimport) + #endif + #else + #define GR_API __attribute__((visibility("default"))) + #endif +#else + #define GR_API +#endif + +// By now we must have a GR_..._BUILD symbol set to 1, and a decision about +// debug -vs- release +// + +extern GR_API void GrPrintf(const char format[], ...); + +/** + * GR_STRING makes a string of X where X is expanded before conversion to a string + * if X itself contains macros. + */ +#define GR_STRING(X) GR_STRING_IMPL(X) +#define GR_STRING_IMPL(X) #X + +/** + * GR_CONCAT concatenates X and Y where each is expanded before + * contanenation if either contains macros. + */ +#define GR_CONCAT(X,Y) GR_CONCAT_IMPL(X,Y) +#define GR_CONCAT_IMPL(X,Y) X##Y + +/** + * Creates a string of the form "<filename>(<linenumber>) : " + */ +#define GR_FILE_AND_LINE_STR __FILE__ "(" GR_STRING(__LINE__) ") : " + +/** + * Compilers have different ways of issuing warnings. This macro + * attempts to abstract them, but may need to be specialized for your + * particular compiler. + * To insert compiler warnings use "#pragma message GR_WARN(<string>)" + */ +#if defined(_MSC_VER) && _MSC_VER + #define GR_WARN(MSG) (GR_FILE_AND_LINE_STR "WARNING: " MSG) +#else//__GNUC__ - may need other defines for different compilers + #define GR_WARN(MSG) ("WARNING: " MSG) +#endif + +/** + * GR_ALWAYSBREAK is an unconditional break in all builds. + */ +#if !defined(GR_ALWAYSBREAK) + #if GR_WIN32_BUILD + #define GR_ALWAYSBREAK SkNO_RETURN_HINT(); __debugbreak() + #else + // TODO: do other platforms really not have continuable breakpoints? + // sign extend for 64bit architectures to be sure this is + // in the high address range + #define GR_ALWAYSBREAK SkNO_RETURN_HINT(); *((int*)(int64_t)(int32_t)0xbeefcafe) = 0; + #endif +#endif + +/** + * GR_DEBUGBREAK is an unconditional break in debug builds. + */ +#if !defined(GR_DEBUGBREAK) + #if GR_DEBUG + #define GR_DEBUGBREAK GR_ALWAYSBREAK + #else + #define GR_DEBUGBREAK + #endif +#endif + +/** + * GR_ALWAYSASSERT is an assertion in all builds. + */ +#if !defined(GR_ALWAYSASSERT) + #define GR_ALWAYSASSERT(COND) \ + do { \ + if (!(COND)) { \ + GrPrintf("%s %s failed\n", GR_FILE_AND_LINE_STR, #COND); \ + GR_ALWAYSBREAK; \ + } \ + } while (false) +#endif + +/** + * GR_DEBUGASSERT is an assertion in debug builds only. + */ +#if !defined(GR_DEBUGASSERT) + #if GR_DEBUG + #define GR_DEBUGASSERT(COND) GR_ALWAYSASSERT(COND) + #else + #define GR_DEBUGASSERT(COND) + #endif +#endif + +/** + * Prettier forms of the above macros. + */ +#define GrAssert(COND) GR_DEBUGASSERT(COND) +#define GrAlwaysAssert(COND) GR_ALWAYSASSERT(COND) + +/** + * Crash from unrecoverable condition, optionally with a message. + */ +inline void GrCrash() { GrAlwaysAssert(false); } +inline void GrCrash(const char* msg) { GrPrintf(msg); GrAlwaysAssert(false); } + +/** + * GR_DEBUGCODE compiles the code X in debug builds only + */ +#if !defined(GR_DEBUGCODE) + #if GR_DEBUG + #define GR_DEBUGCODE(X) X + #else + #define GR_DEBUGCODE(X) + #endif +#endif + +/** + * GR_STATIC_ASSERT is a compile time assertion. Depending on the platform + * it may print the message in the compiler log. Obviously, the condition must + * be evaluatable at compile time. + */ +// VS 2010 and GCC compiled with c++0x or gnu++0x support the new +// static_assert. +#if !defined(GR_STATIC_ASSERT) + #if (defined(_MSC_VER) && _MSC_VER >= 1600) || (defined(__GXX_EXPERIMENTAL_CXX0X__) && __GXX_EXPERIMENTAL_CXX0X__) + #define GR_STATIC_ASSERT(CONDITION) static_assert(CONDITION, "bug") + #else + template <bool> class GR_STATIC_ASSERT_FAILURE; + template <> class GR_STATIC_ASSERT_FAILURE<true> {}; + #define GR_STATIC_ASSERT(CONDITION) \ + enum {GR_CONCAT(X,__LINE__) = \ + sizeof(GR_STATIC_ASSERT_FAILURE<CONDITION>)} + #endif +#endif + +#if !defined(GR_SCALAR_IS_FLOAT) + #define GR_SCALAR_IS_FLOAT 0 +#endif +#if !defined(GR_SCALAR_IS_FIXED) + #define GR_SCALAR_IS_FIXED 0 +#endif + +#if !defined(GR_TEXT_SCALAR_TYPE_IS_USHORT) + #define GR_TEXT_SCALAR_TYPE_IS_USHORT 0 +#endif +#if !defined(GR_TEXT_SCALAR_TYPE_IS_FLOAT) + #define GR_TEXT_SCALAR_TYPE_IS_FLOAT 0 +#endif +#if !defined(GR_TEXT_SCALAR_TYPE_IS_FIXED) + #define GR_TEXT_SCALAR_TYPE_IS_FIXED 0 +#endif + +#ifndef GR_DUMP_TEXTURE_UPLOAD + #define GR_DUMP_TEXTURE_UPLOAD 0 +#endif + +/** + * GR_COLLECT_STATS controls whether the GrGpu class collects stats. + * If not already defined then collect in debug build but not release. + */ +#if !defined(GR_COLLECT_STATS) + #define GR_COLLECT_STATS GR_DEBUG +#endif + +/** + * GR_STATIC_RECT_VB controls whether rects are drawn by issuing a vertex + * for each corner or using a static vb that is positioned by modifying the + * view / texture matrix. + */ +#if !defined(GR_STATIC_RECT_VB) + #define GR_STATIC_RECT_VB 0 +#endif + +/** + * GR_AGGRESSIVE_SHADER_OPTS controls how aggressively shaders are optimized + * for special cases. On systems where program changes are expensive this + * may not be advantageous. Consecutive draws may no longer use the same + * program. + */ +#if !defined(GR_AGGRESSIVE_SHADER_OPTS) + #define GR_AGGRESSIVE_SHADER_OPTS 1 +#endif + +/** + * GR_GEOM_BUFFER_LOCK_THRESHOLD gives a threshold (in bytes) for when Gr should + * lock a GrGeometryBuffer to update its contents. It will use lock() if the + * size of the updated region is greater than the threshold. Otherwise it will + * use updateData(). + */ +#if !defined(GR_GEOM_BUFFER_LOCK_THRESHOLD) + #define GR_GEOM_BUFFER_LOCK_THRESHOLD (1 << 15) +#endif + +/** + * Enables/disables use of offscreen AA + */ +#if !defined(GR_USE_OFFSCREEN_AA) + #define GR_USE_OFFSCREEN_AA 1 +#endif + +/** + * GR_MAX_OFFSCREEN_AA_SIZE controls the size at which offscreen AA will tile. + * Tiling saves GPU memory by limiting the size of the offscreen buffer. The + * max offscreen may be as large as (4*GR_MAX_OFFSCREEN_AA_SIZE)^2 pixels. + */ +#if !defined(GR_MAX_OFFSCREEN_AA_SIZE) + #define GR_MAX_OFFSCREEN_AA_SIZE 256 +#endif + + +/////////////////////////////////////////////////////////////////////////////// +// tail section: +// +// Now we just assert if we are missing some required define, or if we detect +// and inconsistent combination of defines +// + + +/** + * Only one build target macro should be 1 and the rest should be 0. + */ +#define GR_BUILD_SUM (GR_WIN32_BUILD + GR_MAC_BUILD + GR_IOS_BUILD + GR_ANDROID_BUILD + GR_LINUX_BUILD + GR_QNX_BUILD) +#if 0 == GR_BUILD_SUM + #error "Missing a GR_BUILD define" +#elif 1 != GR_BUILD_SUM + #error "More than one GR_BUILD defined" +#endif + + +#if !GR_SCALAR_IS_FLOAT && !GR_SCALAR_IS_FIXED + #undef GR_SCALAR_IS_FLOAT + #define GR_SCALAR_IS_FLOAT 1 + #pragma message GR_WARN("Scalar type not defined, defaulting to float") +#endif + +#if !GR_TEXT_SCALAR_IS_FLOAT && \ + !GR_TEXT_SCALAR_IS_FIXED && \ + !GR_TEXT_SCALAR_IS_USHORT + #undef GR_TEXT_SCALAR_IS_FLOAT + #define GR_TEXT_SCALAR_IS_FLOAT 1 + #pragma message GR_WARN("Text scalar type not defined, defaulting to float") +#endif + +#if 0 +#if GR_WIN32_BUILD +// #pragma message GR_WARN("GR_WIN32_BUILD") +#endif +#if GR_MAC_BUILD +// #pragma message GR_WARN("GR_MAC_BUILD") +#endif +#if GR_IOS_BUILD +// #pragma message GR_WARN("GR_IOS_BUILD") +#endif +#if GR_ANDROID_BUILD +// #pragma message GR_WARN("GR_ANDROID_BUILD") +#endif +#if GR_LINUX_BUILD +// #pragma message GR_WARN("GR_LINUX_BUILD") +#endif +#if GR_QNX_BUILD +// #pragma message GR_WARN("GR_QNX_BUILD") +#endif +#endif + +#endif + diff --git a/include/gpu/GrContext.h b/include/gpu/GrContext.h new file mode 100644 index 0000000..0308b5d --- /dev/null +++ b/include/gpu/GrContext.h @@ -0,0 +1,881 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef GrContext_DEFINED +#define GrContext_DEFINED + +#include "GrClip.h" +#include "GrPaint.h" +// not strictly needed but requires WK change in LayerTextureUpdaterCanvas to +// remove. +#include "GrRenderTarget.h" + +class GrDrawTarget; +class GrFontCache; +class GrGpu; +struct GrGpuStats; +class GrIndexBuffer; +class GrIndexBufferAllocPool; +class GrInOrderDrawBuffer; +class GrPathRenderer; +class GrPathRendererChain; +class GrResourceEntry; +class GrResourceCache; +class GrStencilBuffer; +class GrVertexBuffer; +class GrVertexBufferAllocPool; + +class GR_API GrContext : public GrRefCnt { +public: + /** + * Creates a GrContext from within a 3D context. + */ + static GrContext* Create(GrEngine engine, + GrPlatform3DContext context3D); + + virtual ~GrContext(); + + /** + * The GrContext normally assumes that no outsider is setting state + * within the underlying 3D API's context/device/whatever. This call informs + * the context that the state was modified and it should resend. Shouldn't + * be called frequently for good performance. + */ + void resetContext(); + + /** + * Abandons all gpu resources, assumes 3D API state is unknown. Call this + * if you have lost the associated GPU context, and thus internal texture, + * buffer, etc. references/IDs are now invalid. Should be called even when + * GrContext is no longer going to be used for two reasons: + * 1) ~GrContext will not try to free the objects in the 3D API. + * 2) If you've created GrResources that outlive the GrContext they will + * be marked as invalid (GrResource::isValid()) and won't attempt to + * free their underlying resource in the 3D API. + * Content drawn since the last GrContext::flush() may be lost. + */ + void contextLost(); + + /** + * Similar to contextLost, but makes no attempt to reset state. + * Use this method when GrContext destruction is pending, but + * the graphics context is destroyed first. + */ + void contextDestroyed(); + + /** + * Frees gpu created by the context. Can be called to reduce GPU memory + * pressure. + */ + void freeGpuResources(); + + /////////////////////////////////////////////////////////////////////////// + // Textures + + /** + * Token that refers to an entry in the texture cache. Returned by + * functions that lock textures. Passed to unlockTexture. + */ + class TextureCacheEntry { + public: + TextureCacheEntry() : fEntry(NULL) {} + TextureCacheEntry(const TextureCacheEntry& e) : fEntry(e.fEntry) {} + TextureCacheEntry& operator= (const TextureCacheEntry& e) { + fEntry = e.fEntry; + return *this; + } + GrTexture* texture() const; + void reset() { fEntry = NULL; } + private: + explicit TextureCacheEntry(GrResourceEntry* entry) { fEntry = entry; } + void set(GrResourceEntry* entry) { fEntry = entry; } + GrResourceEntry* cacheEntry() { return fEntry; } + GrResourceEntry* fEntry; + friend class GrContext; + }; + + /** + * Key generated by client. Should be a unique key on the texture data. + * Does not need to consider that width and height of the texture. Two + * textures with the same TextureKey but different bounds will not collide. + */ + typedef uint64_t TextureKey; + + /** + * Create a new entry, based on the specified key and texture, and return + * its "locked" entry. Must call be balanced with an unlockTexture() call. + * + * @param key A client-generated key that identifies the contents + * of the texture. Respecified to findAndLockTexture + * for subsequent uses of the texture. + * @param sampler The sampler state used to draw a texture may be used + * to determine how to store the pixel data in the texture + * cache. (e.g. different versions may exist for different + * wrap modes on GPUs with limited or no NPOT texture + * support). Only the wrap and filter fields are used. NULL + * implies clamp wrap modes and nearest filtering. + * @param desc Description of the texture properties. + * @param srcData Pointer to the pixel values. + * @param rowBytes The number of bytes between rows of the texture. Zero + * implies tightly packed rows. + */ + TextureCacheEntry createAndLockTexture(TextureKey key, + const GrSamplerState* sampler, + const GrTextureDesc& desc, + void* srcData, size_t rowBytes); + + /** + * Search for an entry based on key and dimensions. If found, "lock" it and + * return it. The entry's texture() function will return NULL if not found. + * Must be balanced with an unlockTexture() call. + * + * @param key A client-generated key that identifies the contents + * of the texture. + * @param width The width of the texture in pixels as specifed in + * the GrTextureDesc originally passed to + * createAndLockTexture + * @param width The height of the texture in pixels as specifed in + * the GrTextureDesc originally passed to + * createAndLockTexture + * @param sampler The sampler state used to draw a texture may be used + * to determine the cache entry used. (e.g. different + * versions may exist for different wrap modes on GPUs with + * limited or no NPOT texture support). Only the wrap and + * filter fields are used. NULL implies clamp wrap modes + * and nearest filtering. + */ + TextureCacheEntry findAndLockTexture(TextureKey key, + int width, + int height, + const GrSamplerState* sampler); + /** + * Determines whether a texture is in the cache. If the texture is found it + * will not be locked or returned. This call does not affect the priority of + * the texture for deletion. + */ + bool isTextureInCache(TextureKey key, + int width, + int height, + const GrSamplerState*) const; + + /** + * Enum that determines how closely a returned scratch texture must match + * a provided GrTextureDesc. + */ + enum ScratchTexMatch { + /** + * Finds a texture that exactly matches the descriptor. + */ + kExact_ScratchTexMatch, + /** + * Finds a texture that approximately matches the descriptor. Will be + * at least as large in width and height as desc specifies. If desc + * specifies that texture is a render target then result will be a + * render target. If desc specifies a render target and doesn't set the + * no stencil flag then result will have a stencil. Format and aa level + * will always match. + */ + kApprox_ScratchTexMatch + }; + + /** + * Returns a texture matching the desc. It's contents are unknown. Subsequent + * requests with the same descriptor are not guaranteed to return the same + * texture. The same texture is guaranteed not be returned again until it is + * unlocked. Must call be balanced with an unlockTexture() call. + * + * Textures created by createAndLockTexture() hide the complications of + * tiling non-power-of-two textures on APIs that don't support this (e.g. + * unextended GLES2). Tiling a npot texture created by lockScratchTexture on + * such an API will create gaps in the tiling pattern. This includes clamp + * mode. (This may be addressed in a future update.) + */ + TextureCacheEntry lockScratchTexture(const GrTextureDesc& desc, ScratchTexMatch match); + + /** + * When done with an entry, call unlockTexture(entry) on it, which returns + * it to the cache, where it may be purged. + */ + void unlockTexture(TextureCacheEntry entry); + + /** + * Creates a texture that is outside the cache. Does not count against + * cache's budget. + */ + GrTexture* createUncachedTexture(const GrTextureDesc&, + void* srcData, + size_t rowBytes); + + /** + * Returns true if the specified use of an indexed texture is supported. + */ + bool supportsIndex8PixelConfig(const GrSamplerState*, + int width, + int height) const; + + /** + * Return the current texture cache limits. + * + * @param maxTextures If non-null, returns maximum number of textures that + * can be held in the cache. + * @param maxTextureBytes If non-null, returns maximum number of bytes of + * texture memory that can be held in the cache. + */ + void getTextureCacheLimits(int* maxTextures, size_t* maxTextureBytes) const; + + /** + * Specify the texture cache limits. If the current cache exceeds either + * of these, it will be purged (LRU) to keep the cache within these limits. + * + * @param maxTextures The maximum number of textures that can be held in + * the cache. + * @param maxTextureBytes The maximum number of bytes of texture memory + * that can be held in the cache. + */ + void setTextureCacheLimits(int maxTextures, size_t maxTextureBytes); + + /** + * Return the max width or height of a texture supported by the current gpu + */ + int getMaxTextureSize() const; + + /** + * Return the max width or height of a render target supported by the + * current gpu + */ + int getMaxRenderTargetSize() const; + + /////////////////////////////////////////////////////////////////////////// + // Render targets + + /** + * Sets the render target. + * @param target the render target to set. (should not be NULL.) + */ + void setRenderTarget(GrRenderTarget* target); + + /** + * Gets the current render target. + * @return the currently bound render target. Should never be NULL. + */ + const GrRenderTarget* getRenderTarget() const; + GrRenderTarget* getRenderTarget(); + + /////////////////////////////////////////////////////////////////////////// + // Platform Surfaces + + /** + * Wraps an existing texture with a GrTexture object. + * + * OpenGL: if the object is a texture Gr may change its GL texture params + * when it is drawn. + * + * @param desc description of the object to create. + * + * @return GrTexture object or NULL on failure. + */ + GrTexture* createPlatformTexture(const GrPlatformTextureDesc& desc); + + /** + * Wraps an existing render target with a GrRenderTarget object. It is + * similar to createPlatformTexture but can be used to draw into surfaces + * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that + * the client will resolve to a texture). + * + * @param desc description of the object to create. + * + * @return GrTexture object or NULL on failure. + */ + GrRenderTarget* createPlatformRenderTarget( + const GrPlatformRenderTargetDesc& desc); + + /** + * This interface is depracted and will be removed in a future revision. + * Callers should use createPlatformTexture or createPlatformRenderTarget + * instead. + * + * Wraps an existing 3D API surface in a GrObject. desc.fFlags determines + * the type of object returned. If kIsTexture is set the returned object + * will be a GrTexture*. Otherwise, it will be a GrRenderTarget*. If both + * are set the render target object is accessible by + * GrTexture::asRenderTarget(). + * + * GL: if the object is a texture Gr may change its GL texture parameters + * when it is drawn. + * + * @param desc description of the object to create. + * @return either a GrTexture* or GrRenderTarget* depending on desc. NULL + * on failure. + */ + GrResource* createPlatformSurface(const GrPlatformSurfaceDesc& desc); + + /////////////////////////////////////////////////////////////////////////// + // Matrix state + + /** + * Gets the current transformation matrix. + * @return the current matrix. + */ + const GrMatrix& getMatrix() const; + + /** + * Sets the transformation matrix. + * @param m the matrix to set. + */ + void setMatrix(const GrMatrix& m); + + /** + * Concats the current matrix. The passed matrix is applied before the + * current matrix. + * @param m the matrix to concat. + */ + void concatMatrix(const GrMatrix& m) const; + + + /////////////////////////////////////////////////////////////////////////// + // Clip state + /** + * Gets the current clip. + * @return the current clip. + */ + const GrClip& getClip() const; + + /** + * Sets the clip. + * @param clip the clip to set. + */ + void setClip(const GrClip& clip); + + /** + * Convenience method for setting the clip to a rect. + * @param rect the rect to set as the new clip. + */ + void setClip(const GrIRect& rect); + + /////////////////////////////////////////////////////////////////////////// + // Draws + + /** + * Clear the entire or rect of the render target, ignoring any clips. + * @param rect the rect to clear or the whole thing if rect is NULL. + * @param color the color to clear to. + */ + void clear(const GrIRect* rect, GrColor color); + + /** + * Draw everywhere (respecting the clip) with the paint. + */ + void drawPaint(const GrPaint& paint); + + /** + * Draw the rect using a paint. + * @param paint describes how to color pixels. + * @param strokeWidth If strokeWidth < 0, then the rect is filled, else + * the rect is mitered stroked based on strokeWidth. If + * strokeWidth == 0, then the stroke is always a single + * pixel thick. + * @param matrix Optional matrix applied to the rect. Applied before + * context's matrix or the paint's matrix. + * The rects coords are used to access the paint (through texture matrix) + */ + void drawRect(const GrPaint& paint, + const GrRect&, + GrScalar strokeWidth = -1, + const GrMatrix* matrix = NULL); + + /** + * Maps a rect of paint coordinates onto the a rect of destination + * coordinates. Each rect can optionally be transformed. The srcRect + * is stretched over the dstRect. The dstRect is transformed by the + * context's matrix and the srcRect is transformed by the paint's matrix. + * Additional optional matrices can be provided by parameters. + * + * @param paint describes how to color pixels. + * @param dstRect the destination rect to draw. + * @param srcRect rect of paint coordinates to be mapped onto dstRect + * @param dstMatrix Optional matrix to transform dstRect. Applied before + * context's matrix. + * @param srcMatrix Optional matrix to transform srcRect Applied before + * paint's matrix. + */ + void drawRectToRect(const GrPaint& paint, + const GrRect& dstRect, + const GrRect& srcRect, + const GrMatrix* dstMatrix = NULL, + const GrMatrix* srcMatrix = NULL); + + /** + * Draws a path. + * + * @param paint describes how to color pixels. + * @param path the path to draw + * @param fill the path filling rule to use. + * @param translate optional additional translation applied to the + * path. + */ + void drawPath(const GrPaint& paint, const GrPath& path, GrPathFill fill, + const GrPoint* translate = NULL); + + /** + * Draws vertices with a paint. + * + * @param paint describes how to color pixels. + * @param primitiveType primitives type to draw. + * @param vertexCount number of vertices. + * @param positions array of vertex positions, required. + * @param texCoords optional array of texture coordinates used + * to access the paint. + * @param colors optional array of per-vertex colors, supercedes + * the paint's color field. + * @param indices optional array of indices. If NULL vertices + * are drawn non-indexed. + * @param indexCount if indices is non-null then this is the + * number of indices. + */ + void drawVertices(const GrPaint& paint, + GrPrimitiveType primitiveType, + int vertexCount, + const GrPoint positions[], + const GrPoint texs[], + const GrColor colors[], + const uint16_t indices[], + int indexCount); + + /////////////////////////////////////////////////////////////////////////// + // Misc. + + /** + * Flags that affect flush() behavior. + */ + enum FlushBits { + /** + * A client may want Gr to bind a GrRenderTarget in the 3D API so that + * it can be rendered to directly. However, Gr lazily sets state. Simply + * calling setRenderTarget() followed by flush() without flags may not + * bind the render target. This flag forces the context to bind the last + * set render target in the 3D API. + */ + kForceCurrentRenderTarget_FlushBit = 0x1, + /** + * A client may reach a point where it has partially rendered a frame + * through a GrContext that it knows the user will never see. This flag + * causes the flush to skip submission of deferred content to the 3D API + * during the flush. + */ + kDiscard_FlushBit = 0x2, + }; + + /** + * Call to ensure all drawing to the context has been issued to the + * underlying 3D API. + * @param flagsBitfield flags that control the flushing behavior. See + * FlushBits. + */ + void flush(int flagsBitfield = 0); + + /** + * Reads a rectangle of pixels from a render target. + * @param target the render target to read from. NULL means the + * current render target. + * @param left left edge of the rectangle to read (inclusive) + * @param top top edge of the rectangle to read (inclusive) + * @param width width of rectangle to read in pixels. + * @param height height of rectangle to read in pixels. + * @param config the pixel config of the destination buffer + * @param buffer memory to read the rectangle into. + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + * + * @return true if the read succeeded, false if not. The read can fail + * because of an unsupported pixel config or because no render + * target is currently set. + */ + bool readRenderTargetPixels(GrRenderTarget* target, + int left, int top, int width, int height, + GrPixelConfig config, void* buffer, + size_t rowBytes) { + return this->internalReadRenderTargetPixels(target, left, top, + width, height, + config, buffer, + rowBytes, 0); + } + + /** + * Copy the src pixels [buffer, rowbytes, pixelconfig] into a render target + * at the specified rectangle. + * @param target the render target to write into. NULL means the + * current render target. + * @param left left edge of the rectangle to write (inclusive) + * @param top top edge of the rectangle to write (inclusive) + * @param width width of rectangle to write in pixels. + * @param height height of rectangle to write in pixels. + * @param config the pixel config of the source buffer + * @param buffer memory to read the rectangle from. + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + */ + void writeRenderTargetPixels(GrRenderTarget* target, + int left, int top, int width, int height, + GrPixelConfig config, const void* buffer, + size_t rowBytes) { + this->internalWriteRenderTargetPixels(target, left, top, width, height, + config, buffer, rowBytes, 0); + } + + /** + * Reads a rectangle of pixels from a texture. + * @param texture the texture to read from. + * @param left left edge of the rectangle to read (inclusive) + * @param top top edge of the rectangle to read (inclusive) + * @param width width of rectangle to read in pixels. + * @param height height of rectangle to read in pixels. + * @param config the pixel config of the destination buffer + * @param buffer memory to read the rectangle into. + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + * + * @return true if the read succeeded, false if not. The read can fail + * because of an unsupported pixel config. + */ + bool readTexturePixels(GrTexture* texture, + int left, int top, int width, int height, + GrPixelConfig config, void* buffer, + size_t rowBytes) { + return this->internalReadTexturePixels(texture, left, top, + width, height, + config, buffer, rowBytes, 0); + } + + /** + * Writes a rectangle of pixels to a texture. + * @param texture the render target to read from. + * @param left left edge of the rectangle to write (inclusive) + * @param top top edge of the rectangle to write (inclusive) + * @param width width of rectangle to write in pixels. + * @param height height of rectangle to write in pixels. + * @param config the pixel config of the source buffer + * @param buffer memory to read pixels from + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + */ + void writeTexturePixels(GrTexture* texture, + int left, int top, int width, int height, + GrPixelConfig config, const void* buffer, + size_t rowBytes) { + this->internalWriteTexturePixels(texture, left, top, width, height, + config, buffer, rowBytes, 0); + } + /** + * Copies all texels from one texture to another. + * @param src the texture to copy from. + * @param dst the render target to copy to. + */ + void copyTexture(GrTexture* src, GrRenderTarget* dst); + /** + * Applies a 1D convolution kernel in the X direction to a rectangle of + * pixels from a given texture. + * @param texture the texture to read from + * @param rect the destination rectangle + * @param kernel the convolution kernel (kernelWidth elements) + * @param kernelWidth the width of the convolution kernel + */ + void convolveInX(GrTexture* texture, + const SkRect& rect, + const float* kernel, + int kernelWidth); + /** + * Applies a 1D convolution kernel in the Y direction to a rectangle of + * pixels from a given texture. + * direction. + * @param texture the texture to read from + * @param rect the destination rectangle + * @param kernel the convolution kernel (kernelWidth elements) + * @param kernelWidth the width of the convolution kernel + */ + void convolveInY(GrTexture* texture, + const SkRect& rect, + const float* kernel, + int kernelWidth); + /////////////////////////////////////////////////////////////////////////// + // Helpers + + class AutoRenderTarget : ::GrNoncopyable { + public: + AutoRenderTarget(GrContext* context, GrRenderTarget* target) { + fContext = NULL; + fPrevTarget = context->getRenderTarget(); + if (fPrevTarget != target) { + context->setRenderTarget(target); + fContext = context; + } + } + ~AutoRenderTarget() { + if (fContext) { + fContext->setRenderTarget(fPrevTarget); + } + } + private: + GrContext* fContext; + GrRenderTarget* fPrevTarget; + }; + + + /////////////////////////////////////////////////////////////////////////// + // Functions intended for internal use only. + GrGpu* getGpu() { return fGpu; } + const GrGpu* getGpu() const { return fGpu; } + GrFontCache* getFontCache() { return fFontCache; } + GrDrawTarget* getTextTarget(const GrPaint& paint); + void flushText(); + const GrIndexBuffer* getQuadIndexBuffer() const; + void resetStats(); + const GrGpuStats& getStats() const; + void printStats() const; + /** + * Stencil buffers add themselves to the cache using + * addAndLockStencilBuffer. When a SB's RT-attachment count + * reaches zero the SB unlocks itself using unlockStencilBuffer and is + * eligible for purging. findStencilBuffer is called to check the cache for + * a SB that matching an RT's criteria. If a match is found that has been + * unlocked (its attachment count has reached 0) then it will be relocked. + */ + GrResourceEntry* addAndLockStencilBuffer(GrStencilBuffer* sb); + void unlockStencilBuffer(GrResourceEntry* sbEntry); + GrStencilBuffer* findStencilBuffer(int width, int height, int sampleCnt); + +private: + // used to keep track of when we need to flush the draw buffer + enum DrawCategory { + kBuffered_DrawCategory, // last draw was inserted in draw buffer + kUnbuffered_DrawCategory, // last draw was not inserted in the draw buffer + kText_DrawCategory // text context was last to draw + }; + DrawCategory fLastDrawCategory; + + GrGpu* fGpu; + GrResourceCache* fTextureCache; + GrFontCache* fFontCache; + + GrPathRendererChain* fPathRendererChain; + + GrVertexBufferAllocPool* fDrawBufferVBAllocPool; + GrIndexBufferAllocPool* fDrawBufferIBAllocPool; + GrInOrderDrawBuffer* fDrawBuffer; + + GrIndexBuffer* fAAFillRectIndexBuffer; + GrIndexBuffer* fAAStrokeRectIndexBuffer; + int fMaxOffscreenAASize; + + GrContext(GrGpu* gpu); + + void fillAARect(GrDrawTarget* target, + const GrRect& devRect, + bool useVertexCoverage); + + void strokeAARect(GrDrawTarget* target, + const GrRect& devRect, + const GrVec& devStrokeSize, + bool useVertexCoverage); + + inline int aaFillRectIndexCount() const; + GrIndexBuffer* aaFillRectIndexBuffer(); + + inline int aaStrokeRectIndexCount() const; + GrIndexBuffer* aaStrokeRectIndexBuffer(); + + void setupDrawBuffer(); + + void flushDrawBuffer(); + + void setPaint(const GrPaint& paint, GrDrawTarget* target); + + GrDrawTarget* prepareToDraw(const GrPaint& paint, DrawCategory drawType); + + GrPathRenderer* getPathRenderer(const GrPath& path, + GrPathFill fill, + bool antiAlias); + + struct OffscreenRecord; + + // determines whether offscreen AA should be applied + bool doOffscreenAA(GrDrawTarget* target, + bool isHairLines) const; + + // attempts to setup offscreen AA. All paint state must be transferred to + // target by the time this is called. + bool prepareForOffscreenAA(GrDrawTarget* target, + bool requireStencil, + const GrIRect& boundRect, + GrPathRenderer* pr, + OffscreenRecord* record); + + // sets up target to draw coverage to the supersampled render target + void setupOffscreenAAPass1(GrDrawTarget* target, + const GrIRect& boundRect, + int tileX, int tileY, + OffscreenRecord* record); + + // sets up target to sample coverage of supersampled render target back + // to the main render target using stage kOffscreenStage. + void doOffscreenAAPass2(GrDrawTarget* target, + const GrPaint& paint, + const GrIRect& boundRect, + int tileX, int tileY, + OffscreenRecord* record); + + // restored the draw target state and releases offscreen target to cache + void cleanupOffscreenAA(GrDrawTarget* target, + GrPathRenderer* pr, + OffscreenRecord* record); + + void convolve(GrTexture* texture, + const SkRect& rect, + float imageIncrement[2], + const float* kernel, + int kernelWidth); + + /** + * Flags to the internal read/write pixels funcs + */ + enum PixelOpsFlags { + kDontFlush_PixelOpsFlag = 0x1, + }; + + bool internalReadRenderTargetPixels(GrRenderTarget* target, + int left, int top, + int width, int height, + GrPixelConfig config, void* buffer, + size_t rowBytes, uint32_t flags); + + void internalWriteRenderTargetPixels(GrRenderTarget* target, + int left, int top, + int width, int height, + GrPixelConfig, const void* buffer, + size_t rowBytes, uint32_t flags); + + bool internalReadTexturePixels(GrTexture* texture, + int left, int top, + int width, int height, + GrPixelConfig config, void* buffer, + size_t rowBytes, uint32_t flags); + + void internalWriteTexturePixels(GrTexture* texture, + int left, int top, + int width, int height, + GrPixelConfig config, const void* buffer, + size_t rowBytes, uint32_t flags); + // needed for access to internalWriteTexturePixels. TODO: make GrContext + // be a facade for an internal class. Then functions that are public on the + // internal class would have only be callable in src/gpu. The facade would + // only have to functions necessary for clients. + friend class GrAtlas; + + // computes vertex layout bits based on the paint. If paint expresses + // a texture for a stage, the stage coords will be bound to postitions + // unless hasTexCoords[s]==true in which case stage s's input coords + // are bound to tex coord index s. hasTexCoords == NULL is a shortcut + // for an array where all the values are false. + static int PaintStageVertexLayoutBits( + const GrPaint& paint, + const bool hasTexCoords[GrPaint::kTotalStages]); + +}; + +/** + * Save/restore the view-matrix in the context. + */ +class GrAutoMatrix : GrNoncopyable { +public: + GrAutoMatrix() : fContext(NULL) {} + GrAutoMatrix(GrContext* ctx) : fContext(ctx) { + fMatrix = ctx->getMatrix(); + } + GrAutoMatrix(GrContext* ctx, const GrMatrix& matrix) : fContext(ctx) { + fMatrix = ctx->getMatrix(); + ctx->setMatrix(matrix); + } + void set(GrContext* ctx) { + if (NULL != fContext) { + fContext->setMatrix(fMatrix); + } + fMatrix = ctx->getMatrix(); + fContext = ctx; + } + void set(GrContext* ctx, const GrMatrix& matrix) { + if (NULL != fContext) { + fContext->setMatrix(fMatrix); + } + fMatrix = ctx->getMatrix(); + ctx->setMatrix(matrix); + fContext = ctx; + } + ~GrAutoMatrix() { + if (NULL != fContext) { + fContext->setMatrix(fMatrix); + } + } + +private: + GrContext* fContext; + GrMatrix fMatrix; +}; + +/** + * Gets and locks a scratch texture from a descriptor using + * either exact or approximate criteria. Unlocks texture in + * the destructor. + */ +class GrAutoScratchTexture : ::GrNoncopyable { +public: + GrAutoScratchTexture() + : fContext(NULL) { + } + + GrAutoScratchTexture(GrContext* context, + const GrTextureDesc& desc, + GrContext::ScratchTexMatch match = + GrContext::kApprox_ScratchTexMatch) + : fContext(NULL) { + this->set(context, desc, match); + } + + ~GrAutoScratchTexture() { + if (NULL != fContext) { + fContext->unlockTexture(fEntry); + } + } + + GrTexture* set(GrContext* context, + const GrTextureDesc& desc, + GrContext::ScratchTexMatch match = + GrContext::kApprox_ScratchTexMatch) { + if (NULL != fContext) { + fContext->unlockTexture(fEntry); + } + fContext = context; + if (NULL != fContext) { + fEntry = fContext->lockScratchTexture(desc, match); + GrTexture* ret = fEntry.texture(); + if (NULL == ret) { + fContext = NULL; + } + return ret; + } else { + return NULL; + } + } + + GrTexture* texture() { return fEntry.texture(); } +private: + GrContext* fContext; + GrContext::TextureCacheEntry fEntry; +}; + +#endif + diff --git a/include/gpu/GrFontScaler.h b/include/gpu/GrFontScaler.h new file mode 100644 index 0000000..657647d --- /dev/null +++ b/include/gpu/GrFontScaler.h @@ -0,0 +1,37 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrFontScaler_DEFINED +#define GrFontScaler_DEFINED + +#include "GrGlyph.h" +#include "GrKey.h" + +class SkPath; + +/** + * This is a virtual base class which Gr's interface to the host platform's + * font scaler. + * + * The client is responsible for subclassing, and instantiating this. The + * instance is create for a specific font+size+matrix. + */ +class GrFontScaler : public GrRefCnt { +public: + virtual const GrKey* getKey() = 0; + virtual GrMaskFormat getMaskFormat() = 0; + virtual bool getPackedGlyphBounds(GrGlyph::PackedID, GrIRect* bounds) = 0; + virtual bool getPackedGlyphImage(GrGlyph::PackedID, int width, int height, + int rowBytes, void* image) = 0; + virtual bool getGlyphPath(uint16_t glyphID, SkPath*) = 0; +}; + +#endif + diff --git a/include/gpu/GrGLConfig.h b/include/gpu/GrGLConfig.h new file mode 100644 index 0000000..c9aaec5 --- /dev/null +++ b/include/gpu/GrGLConfig.h @@ -0,0 +1,252 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrGLConfig_DEFINED +#define GrGLConfig_DEFINED + +#include "GrTypes.h" +#include "GrGLDefines.h" + +/** + * Optional GL config file. + */ +#ifdef GR_GL_CUSTOM_SETUP_HEADER + #include GR_GL_CUSTOM_SETUP_HEADER +#endif + +#if !defined(GR_GL_FUNCTION_TYPE) + #define GR_GL_FUNCTION_TYPE +#endif + +/** + * The following are optional defines that can be enabled at the compiler + * command line, in a IDE project, in a GrUserConfig.h file, or in a GL custom + * file (if one is in use). If a GR_GL_CUSTOM_SETUP_HEADER is used they can + * also be placed there. + * + * GR_GL_LOG_CALLS: if 1 Gr can print every GL call using GrPrintf. Defaults to + * 0. Logging can be enabled and disabled at runtime using a debugger via to + * global gLogCallsGL. The initial value of gLogCallsGL is controlled by + * GR_GL_LOG_CALLS_START. + * + * GR_GL_LOG_CALLS_START: controls the initial value of gLogCallsGL when + * GR_GL_LOG_CALLS is 1. Defaults to 0. + * + * GR_GL_CHECK_ERROR: if enabled Gr can do a glGetError() after every GL call. + * Defaults to 1 if GR_DEBUG is set, otherwise 0. When GR_GL_CHECK_ERROR is 1 + * this can be toggled in a debugger using the gCheckErrorGL global. The initial + * value of gCheckErrorGL is controlled by by GR_GL_CHECK_ERROR_START. + * + * GR_GL_CHECK_ERROR_START: controls the initial value of gCheckErrorGL + * when GR_GL_CHECK_ERROR is 1. Defaults to 1. + * + * GR_GL_NO_CONSTANT_ATTRIBUTES: if this evaluates to true then the GL backend + * will use uniforms instead of attributes in all cases when there is not + * per-vertex data. This is important when the underlying GL implementation + * doesn't actually support immediate style attribute values (e.g. when + * the GL stream is converted to DX as in ANGLE on Chrome). Defaults to 0. + * + * GR_GL_ATTRIBUTE_MATRICES: If changing uniforms is very expensive it may be + * faster to use vertex attributes for matrices (set via glVertexAttrib3fv). + * Setting this build flag enables this behavior. GR_GL_NO_CONSTANT_ATTRIBUTES + * must not be set since this uses constant attributes for the matrices. + * Defaults to 0. + * + * GR_GL_USE_BUFFER_DATA_NULL_HINT: When specifing new data for a vertex/index + * buffer that replaces old data Ganesh can give a hint to the driver that the + * previous data will not be used in future draws like this: + * glBufferData(GL_..._BUFFER, size, NULL, usage); //<--hint, NULL means + * glBufferSubData(GL_..._BUFFER, 0, lessThanSize, data) // old data can't be + * // used again. + * However, this can be an unoptimization on some platforms, esp. Chrome. + * Chrome's cmd buffer will create a new allocation and memset the whole thing + * to zero (for security reasons). Defaults to 1 (enabled). + * + * GR_GL_PER_GL_FUNC_CALLBACK: When set to 1 the GrGLInterface object provides + * a function pointer that is called just before every gl function. The ptr must + * be valid (i.e. there is no NULL check). However, by default the callback will + * be set to a function that does nothing. The signature of the function is: + * void function(const GrGLInterface*) + * It is not extern "C". + * The GrGLInterface field fCallback specifies the function ptr and there is an + * additional field fCallbackData of type intptr_t for client data. + * + * GR_GL_RGBA_8888_PIXEL_OPS_SLOW: Set this to 1 if it is known that performing + * glReadPixels / glTex(Sub)Image with format=GL_RGBA, type=GL_UNISIGNED_BYTE is + * significantly slower than format=GL_BGRA, type=GL_UNISIGNED_BYTE. + * + * GR_GL_FULL_READPIXELS_FASTER_THAN_PARTIAL: Set this to 1 if calling + * glReadPixels to read the entire framebuffer is faster than calling it with + * the same sized rectangle but with a framebuffer bound that is larger than + * the rectangle read. + */ + +#if !defined(GR_GL_LOG_CALLS) + #define GR_GL_LOG_CALLS GR_DEBUG +#endif + +#if !defined(GR_GL_LOG_CALLS_START) + #define GR_GL_LOG_CALLS_START 0 +#endif + +#if !defined(GR_GL_CHECK_ERROR) + #define GR_GL_CHECK_ERROR GR_DEBUG +#endif + +#if !defined(GR_GL_CHECK_ERROR_START) + #define GR_GL_CHECK_ERROR_START 1 +#endif + +#if !defined(GR_GL_NO_CONSTANT_ATTRIBUTES) + #define GR_GL_NO_CONSTANT_ATTRIBUTES 0 +#endif + +#if !defined(GR_GL_ATTRIBUTE_MATRICES) + #define GR_GL_ATTRIBUTE_MATRICES 0 +#endif + +#if !defined(GR_GL_USE_BUFFER_DATA_NULL_HINT) + #define GR_GL_USE_BUFFER_DATA_NULL_HINT 1 +#endif + +#if !defined(GR_GL_PER_GL_FUNC_CALLBACK) + #define GR_GL_PER_GL_FUNC_CALLBACK 0 +#endif + +#if !defined(GR_GL_RGBA_8888_PIXEL_OPS_SLOW) + #define GR_GL_RGBA_8888_PIXEL_OPS_SLOW 0 +#endif + +#if !defined(GR_GL_FULL_READPIXELS_FASTER_THAN_PARTIAL) + #define GR_GL_FULL_READPIXELS_FASTER_THAN_PARTIAL 0 +#endif + +#if(GR_GL_NO_CONSTANT_ATTRIBUTES) && (GR_GL_ATTRIBUTE_MATRICES) + #error "Cannot combine GR_GL_NO_CONSTANT_ATTRIBUTES and GR_GL_ATTRIBUTE_MATRICES" +#endif + +//////////////////////////////////////////////////////////////////////////////// + +#if GR_SCALAR_IS_FIXED + #define GrGLType GL_FIXED +#elif GR_SCALAR_IS_FLOAT + #define GrGLType GR_GL_FLOAT +#else + #error "unknown GR_SCALAR type" +#endif + +#if GR_TEXT_SCALAR_IS_USHORT + #define GrGLTextType GR_GL_UNSIGNED_SHORT + #define GR_GL_TEXT_TEXTURE_NORMALIZED 1 +#elif GR_TEXT_SCALAR_IS_FLOAT + #define GrGLTextType GR_GL_FLOAT + #define GR_GL_TEXT_TEXTURE_NORMALIZED 0 +#elif GR_TEXT_SCALAR_IS_FIXED + #define GrGLTextType GR_GL_FIXED + #define GR_GL_TEXT_TEXTURE_NORMALIZED 0 +#else + #error "unknown GR_TEXT_SCALAR type" +#endif + +//////////////////////////////////////////////////////////////////////////////// + +struct GrGLInterface; + +extern void GrGLCheckErr(const GrGLInterface* gl, + const char* location, + const char* call); + +extern void GrGLClearErr(const GrGLInterface* gl); + +#if GR_GL_CHECK_ERROR + extern bool gCheckErrorGL; + #define GR_GL_CHECK_ERROR_IMPL(IFACE, X) \ + if (gCheckErrorGL) \ + GrGLCheckErr(IFACE, GR_FILE_AND_LINE_STR, #X) +#else + #define GR_GL_CHECK_ERROR_IMPL(IFACE, X) +#endif + +#if GR_GL_LOG_CALLS + extern bool gLogCallsGL; + #define GR_GL_LOG_CALLS_IMPL(X) \ + if (gLogCallsGL) \ + GrPrintf(GR_FILE_AND_LINE_STR "GL: " #X "\n") +#else + #define GR_GL_LOG_CALLS_IMPL(X) +#endif + +#if GR_GL_PER_GL_FUNC_CALLBACK + #define GR_GL_CALLBACK_IMPL(IFACE) (IFACE)->fCallback(IFACE) +#else + #define GR_GL_CALLBACK_IMPL(IFACE) +#endif + +#define GR_GL_CALL(IFACE, X) \ + do { \ + GR_GL_CALL_NOERRCHECK(IFACE, X); \ + GR_GL_CHECK_ERROR_IMPL(IFACE, X); \ + } while (false) + +#define GR_GL_CALL_NOERRCHECK(IFACE, X) \ + do { \ + GR_GL_CALLBACK_IMPL(IFACE); \ + (IFACE)->f##X; \ + GR_GL_LOG_CALLS_IMPL(X); \ + } while (false) + +#define GR_GL_CALL_RET(IFACE, RET, X) \ + do { \ + GR_GL_CALL_RET_NOERRCHECK(IFACE, RET, X); \ + GR_GL_CHECK_ERROR_IMPL(IFACE, X); \ + } while (false) + +#define GR_GL_CALL_RET_NOERRCHECK(IFACE, RET, X) \ + do { \ + GR_GL_CALLBACK_IMPL(IFACE); \ + (RET) = (IFACE)->f##X; \ + GR_GL_LOG_CALLS_IMPL(X); \ + } while (false) + +#define GR_GL_GET_ERROR(IFACE) (IFACE)->fGetError() + +//////////////////////////////////////////////////////////////////////////////// + +/** + * Some drivers want the var-int arg to be zero-initialized on input. + */ +#define GR_GL_INIT_ZERO 0 +#define GR_GL_GetIntegerv(gl, e, p) \ + do { \ + *(p) = GR_GL_INIT_ZERO; \ + GR_GL_CALL(gl, GetIntegerv(e, p)); \ + } while (0) + +#define GR_GL_GetFramebufferAttachmentParameteriv(gl, t, a, pname, p) \ + do { \ + *(p) = GR_GL_INIT_ZERO; \ + GR_GL_CALL(gl, GetFramebufferAttachmentParameteriv(t, a, pname, p)); \ + } while (0) + +#define GR_GL_GetRenderbufferParameteriv(gl, t, pname, p) \ + do { \ + *(p) = GR_GL_INIT_ZERO; \ + GR_GL_CALL(gl, GetRenderbufferParameteriv(t, pname, p)); \ + } while (0) + +#define GR_GL_GetTexLevelParameteriv(gl, t, l, pname, p) \ + do { \ + *(p) = GR_GL_INIT_ZERO; \ + GR_GL_CALL(gl, GetTexLevelParameteriv(t, l, pname, p)); \ + } while (0) + +//////////////////////////////////////////////////////////////////////////////// + +#endif diff --git a/include/gpu/GrGLConfig_chrome.h b/include/gpu/GrGLConfig_chrome.h new file mode 100644 index 0000000..ee3c991 --- /dev/null +++ b/include/gpu/GrGLConfig_chrome.h @@ -0,0 +1,30 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef GrGLConfig_chrome_DEFINED +#define GrGLConfig_chrome_DEFINED + +// glGetError() forces a sync with gpu process on chrome +#define GR_GL_CHECK_ERROR_START 0 + +// ANGLE creates a temp VB for vertex attributes not specified per-vertex. +#define GR_GL_NO_CONSTANT_ATTRIBUTES GR_WIN32_BUILD + +// For RGBA teximage/readpixels ANGLE will sw-convert to/from BGRA. +#define GR_GL_RGBA_8888_PIXEL_OPS_SLOW GR_WIN32_BUILD + +// ANGLE can go faster if the entire fbo is read rather than a subrect +#define GR_GL_FULL_READPIXELS_FASTER_THAN_PARTIAL GR_WIN32_BUILD + +// cmd buffer allocates memory and memsets it to zero when it sees glBufferData +// with NULL. +#define GR_GL_USE_BUFFER_DATA_NULL_HINT 0 + +// chrome uses this to set the context on each GL call. +#define GR_GL_PER_GL_FUNC_CALLBACK 1 + +#endif diff --git a/include/gpu/GrGLDefines.h b/include/gpu/GrGLDefines.h new file mode 100644 index 0000000..e66eec4 --- /dev/null +++ b/include/gpu/GrGLDefines.h @@ -0,0 +1,692 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrGLDefines_DEFINED +#define GrGLDefines_DEFINED + +// The following constants consist of the intersection of GL constants +// exported by GLES 1.0, GLES 2.0, and desktop GL required by the system. + +#define GR_GL_DEPTH_BUFFER_BIT 0x00000100 +#define GR_GL_STENCIL_BUFFER_BIT 0x00000400 +#define GR_GL_COLOR_BUFFER_BIT 0x00004000 + +/* Boolean */ +#define GR_GL_FALSE 0 +#define GR_GL_TRUE 1 + +/* BeginMode */ +#define GR_GL_POINTS 0x0000 +#define GR_GL_LINES 0x0001 +#define GR_GL_LINE_LOOP 0x0002 +#define GR_GL_LINE_STRIP 0x0003 +#define GR_GL_TRIANGLES 0x0004 +#define GR_GL_TRIANGLE_STRIP 0x0005 +#define GR_GL_TRIANGLE_FAN 0x0006 + +/* AlphaFunction (not supported in ES20) */ +/* GL_NEVER */ +/* GL_LESS */ +/* GL_EQUAL */ +/* GL_LEQUAL */ +/* GL_GREATER */ +/* GL_NOTEQUAL */ +/* GL_GEQUAL */ +/* GL_ALWAYS */ + +/* BlendingFactorDest */ +#define GR_GL_ZERO 0 +#define GR_GL_ONE 1 +#define GR_GL_SRC_COLOR 0x0300 +#define GR_GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GR_GL_SRC_ALPHA 0x0302 +#define GR_GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GR_GL_DST_ALPHA 0x0304 +#define GR_GL_ONE_MINUS_DST_ALPHA 0x0305 + +/* BlendingFactorSrc */ +/* GL_ZERO */ +/* GL_ONE */ +#define GR_GL_DST_COLOR 0x0306 +#define GR_GL_ONE_MINUS_DST_COLOR 0x0307 +#define GR_GL_SRC_ALPHA_SATURATE 0x0308 +/* GL_SRC_ALPHA */ +/* GL_ONE_MINUS_SRC_ALPHA */ +/* GL_DST_ALPHA */ +/* GL_ONE_MINUS_DST_ALPHA */ + +/* ExtendedBlendFactors */ +#define GR_GL_SRC1_COLOR 0x88F9 +#define GR_GL_ONE_MINUS_SRC1_COLOR 0x88FA +/* GL_SRC1_ALPHA */ +#define GR_GL_ONE_MINUS_SRC1_ALPHA 0x88FB + +/* BlendEquationSeparate */ +#define GR_GL_FUNC_ADD 0x8006 +#define GR_GL_BLEND_EQUATION 0x8009 +#define GR_GL_BLEND_EQUATION_RGB 0x8009 /* same as BLEND_EQUATION */ +#define GR_GL_BLEND_EQUATION_ALPHA 0x883D + +/* BlendSubtract */ +#define GR_GL_FUNC_SUBTRACT 0x800A +#define GR_GL_FUNC_REVERSE_SUBTRACT 0x800B + +/* Separate Blend Functions */ +#define GR_GL_BLEND_DST_RGB 0x80C8 +#define GR_GL_BLEND_SRC_RGB 0x80C9 +#define GR_GL_BLEND_DST_ALPHA 0x80CA +#define GR_GL_BLEND_SRC_ALPHA 0x80CB +#define GR_GL_CONSTANT_COLOR 0x8001 +#define GR_GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GR_GL_CONSTANT_ALPHA 0x8003 +#define GR_GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GR_GL_BLEND_COLOR 0x8005 + +/* Buffer Objects */ +#define GR_GL_ARRAY_BUFFER 0x8892 +#define GR_GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GR_GL_ARRAY_BUFFER_BINDING 0x8894 +#define GR_GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 + +#define GR_GL_STREAM_DRAW 0x88E0 +#define GR_GL_STATIC_DRAW 0x88E4 +#define GR_GL_DYNAMIC_DRAW 0x88E8 + +#define GR_GL_BUFFER_SIZE 0x8764 +#define GR_GL_BUFFER_USAGE 0x8765 + +#define GR_GL_CURRENT_VERTEX_ATTRIB 0x8626 + +/* CullFaceMode */ +#define GR_GL_FRONT 0x0404 +#define GR_GL_BACK 0x0405 +#define GR_GL_FRONT_AND_BACK 0x0408 + +/* DepthFunction */ +/* GL_NEVER */ +/* GL_LESS */ +/* GL_EQUAL */ +/* GL_LEQUAL */ +/* GL_GREATER */ +/* GL_NOTEQUAL */ +/* GL_GEQUAL */ +/* GL_ALWAYS */ + +/* EnableCap */ +#define GR_GL_TEXTURE_2D 0x0DE1 +#define GR_GL_CULL_FACE 0x0B44 +#define GR_GL_BLEND 0x0BE2 +#define GR_GL_DITHER 0x0BD0 +#define GR_GL_STENCIL_TEST 0x0B90 +#define GR_GL_DEPTH_TEST 0x0B71 +#define GR_GL_SCISSOR_TEST 0x0C11 +#define GR_GL_POLYGON_OFFSET_FILL 0x8037 +#define GR_GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GR_GL_SAMPLE_COVERAGE 0x80A0 + +/* ErrorCode */ +#define GR_GL_NO_ERROR 0 +#define GR_GL_INVALID_ENUM 0x0500 +#define GR_GL_INVALID_VALUE 0x0501 +#define GR_GL_INVALID_OPERATION 0x0502 +#define GR_GL_OUT_OF_MEMORY 0x0505 +#define GR_GL_CONTEXT_LOST 0x300E // TODO(gman): What value? + +/* FrontFaceDirection */ +#define GR_GL_CW 0x0900 +#define GR_GL_CCW 0x0901 + +/* GetPName */ +#define GR_GL_LINE_WIDTH 0x0B21 +#define GR_GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GR_GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GR_GL_CULL_FACE_MODE 0x0B45 +#define GR_GL_FRONT_FACE 0x0B46 +#define GR_GL_DEPTH_RANGE 0x0B70 +#define GR_GL_DEPTH_WRITEMASK 0x0B72 +#define GR_GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GR_GL_DEPTH_FUNC 0x0B74 +#define GR_GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GR_GL_STENCIL_FUNC 0x0B92 +#define GR_GL_STENCIL_FAIL 0x0B94 +#define GR_GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GR_GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GR_GL_STENCIL_REF 0x0B97 +#define GR_GL_STENCIL_VALUE_MASK 0x0B93 +#define GR_GL_STENCIL_WRITEMASK 0x0B98 +#define GR_GL_STENCIL_BACK_FUNC 0x8800 +#define GR_GL_STENCIL_BACK_FAIL 0x8801 +#define GR_GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GR_GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GR_GL_STENCIL_BACK_REF 0x8CA3 +#define GR_GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GR_GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GR_GL_VIEWPORT 0x0BA2 +#define GR_GL_SCISSOR_BOX 0x0C10 +/* GL_SCISSOR_TEST */ +#define GR_GL_COLOR_CLEAR_VALUE 0x0C22 +#define GR_GL_COLOR_WRITEMASK 0x0C23 +#define GR_GL_UNPACK_ALIGNMENT 0x0CF5 +#define GR_GL_UNPACK_FLIP_Y 0x9240 +#define GR_GL_PACK_ALIGNMENT 0x0D05 +#define GR_GL_PACK_REVERSE_ROW_ORDER 0x93A4 +#define GR_GL_MAX_TEXTURE_SIZE 0x0D33 +#define GR_GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GR_GL_SUBPIXEL_BITS 0x0D50 +#define GR_GL_RED_BITS 0x0D52 +#define GR_GL_GREEN_BITS 0x0D53 +#define GR_GL_BLUE_BITS 0x0D54 +#define GR_GL_ALPHA_BITS 0x0D55 +#define GR_GL_DEPTH_BITS 0x0D56 +#define GR_GL_STENCIL_BITS 0x0D57 +#define GR_GL_POLYGON_OFFSET_UNITS 0x2A00 +/* GL_POLYGON_OFFSET_FILL */ +#define GR_GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GR_GL_TEXTURE_BINDING_2D 0x8069 +#define GR_GL_SAMPLE_BUFFERS 0x80A8 +#define GR_GL_SAMPLES 0x80A9 +#define GR_GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GR_GL_SAMPLE_COVERAGE_INVERT 0x80AB + +/* GetTextureParameter */ +/* GL_TEXTURE_MAG_FILTER */ +/* GL_TEXTURE_MIN_FILTER */ +/* GL_TEXTURE_WRAP_S */ +/* GL_TEXTURE_WRAP_T */ + +#define GR_GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GR_GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 + +/* HintMode */ +#define GR_GL_DONT_CARE 0x1100 +#define GR_GL_FASTEST 0x1101 +#define GR_GL_NICEST 0x1102 + +/* HintTarget */ +#define GR_GL_GENERATE_MIPMAP_HINT 0x8192 + +/* DataType */ +#define GR_GL_BYTE 0x1400 +#define GR_GL_UNSIGNED_BYTE 0x1401 +#define GR_GL_SHORT 0x1402 +#define GR_GL_UNSIGNED_SHORT 0x1403 +#define GR_GL_INT 0x1404 +#define GR_GL_UNSIGNED_INT 0x1405 +#define GR_GL_FLOAT 0x1406 +#define GR_GL_FIXED 0x140C + +/* Lighting */ +#define GR_GL_LIGHTING 0x0B50 +#define GR_GL_LIGHT0 0x4000 +#define GR_GL_LIGHT1 0x4001 +#define GR_GL_LIGHT2 0x4002 +#define GR_GL_LIGHT3 0x4003 +#define GR_GL_LIGHT4 0x4004 +#define GR_GL_LIGHT5 0x4005 +#define GR_GL_LIGHT6 0x4006 +#define GR_GL_LIGHT7 0x4007 +#define GR_GL_SPOT_EXPONENT 0x1205 +#define GR_GL_SPOT_CUTOFF 0x1206 +#define GR_GL_CONSTANT_ATTENUATION 0x1207 +#define GR_GL_LINEAR_ATTENUATION 0x1208 +#define GR_GL_QUADRATIC_ATTENUATION 0x1209 +#define GR_GL_AMBIENT 0x1200 +#define GR_GL_DIFFUSE 0x1201 +#define GR_GL_SPECULAR 0x1202 +#define GR_GL_SHININESS 0x1601 +#define GR_GL_EMISSION 0x1600 +#define GR_GL_POSITION 0x1203 +#define GR_GL_SPOT_DIRECTION 0x1204 +#define GR_GL_AMBIENT_AND_DIFFUSE 0x1602 +#define GR_GL_COLOR_INDEXES 0x1603 +#define GR_GL_LIGHT_MODEL_TWO_SIDE 0x0B52 +#define GR_GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 +#define GR_GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GR_GL_FRONT_AND_BACK 0x0408 +#define GR_GL_SHADE_MODEL 0x0B54 +#define GR_GL_FLAT 0x1D00 +#define GR_GL_SMOOTH 0x1D01 +#define GR_GL_COLOR_MATERIAL 0x0B57 +#define GR_GL_COLOR_MATERIAL_FACE 0x0B55 +#define GR_GL_COLOR_MATERIAL_PARAMETER 0x0B56 +#define GR_GL_NORMALIZE 0x0BA1 + +/* Matrix Mode */ +#define GR_GL_MATRIX_MODE 0x0BA0 +#define GR_GL_MODELVIEW 0x1700 +#define GR_GL_PROJECTION 0x1701 +#define GR_GL_TEXTURE 0x1702 + +/* multisample */ +#define GR_GL_MULTISAMPLE 0x809D + +/* Points */ +#define GR_GL_POINT_SMOOTH 0x0B10 +#define GR_GL_POINT_SIZE 0x0B11 +#define GR_GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GR_GL_POINT_SIZE_RANGE 0x0B12 + +/* Lines */ +#define GR_GL_LINE_SMOOTH 0x0B20 +#define GR_GL_LINE_STIPPLE 0x0B24 +#define GR_GL_LINE_STIPPLE_PATTERN 0x0B25 +#define GR_GL_LINE_STIPPLE_REPEAT 0x0B26 +#define GR_GL_LINE_WIDTH 0x0B21 +#define GR_GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GR_GL_LINE_WIDTH_RANGE 0x0B22 + +/* PixelFormat */ +#define GR_GL_DEPTH_COMPONENT 0x1902 +#define GR_GL_RED 0x1903 +#define GR_GL_GREEN 0x1904 +#define GR_GL_BLUE 0x1905 +#define GR_GL_ALPHA 0x1906 +#define GR_GL_RGB 0x1907 +#define GR_GL_RGBA 0x1908 +#define GR_GL_BGRA 0x80E1 +#define GR_GL_LUMINANCE 0x1909 +#define GR_GL_LUMINANCE_ALPHA 0x190A +#define GR_GL_PALETTE8_RGBA8 0x8B96 +#define GR_GL_ALPHA8 0x803C + +/* PixelType */ +/* GL_UNSIGNED_BYTE */ +#define GR_GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GR_GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GR_GL_UNSIGNED_SHORT_5_6_5 0x8363 + +/* Shaders */ +#define GR_GL_FRAGMENT_SHADER 0x8B30 +#define GR_GL_VERTEX_SHADER 0x8B31 +#define GR_GL_GEOMETRY_SHADER 0x8DD9 +#define GR_GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GR_GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GR_GL_MAX_VARYING_VECTORS 0x8DFC +#define GR_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GR_GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GR_GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GR_GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GR_GL_SHADER_TYPE 0x8B4F +#define GR_GL_DELETE_STATUS 0x8B80 +#define GR_GL_LINK_STATUS 0x8B82 +#define GR_GL_VALIDATE_STATUS 0x8B83 +#define GR_GL_ATTACHED_SHADERS 0x8B85 +#define GR_GL_ACTIVE_UNIFORMS 0x8B86 +#define GR_GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GR_GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GR_GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GR_GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GR_GL_CURRENT_PROGRAM 0x8B8D +#define GR_GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GR_GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A + +/* StencilFunction */ +#define GR_GL_NEVER 0x0200 +#define GR_GL_LESS 0x0201 +#define GR_GL_EQUAL 0x0202 +#define GR_GL_LEQUAL 0x0203 +#define GR_GL_GREATER 0x0204 +#define GR_GL_NOTEQUAL 0x0205 +#define GR_GL_GEQUAL 0x0206 +#define GR_GL_ALWAYS 0x0207 + +/* StencilOp */ +/* GL_ZERO */ +#define GR_GL_KEEP 0x1E00 +#define GR_GL_REPLACE 0x1E01 +#define GR_GL_INCR 0x1E02 +#define GR_GL_DECR 0x1E03 +#define GR_GL_INVERT 0x150A +#define GR_GL_INCR_WRAP 0x8507 +#define GR_GL_DECR_WRAP 0x8508 + +/* StringName */ +#define GR_GL_VENDOR 0x1F00 +#define GR_GL_RENDERER 0x1F01 +#define GR_GL_VERSION 0x1F02 +#define GR_GL_EXTENSIONS 0x1F03 + +/* Pixel Mode / Transfer */ +#define GR_GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GR_GL_PACK_ROW_LENGTH 0x0D02 + + +/* TextureMagFilter */ +#define GR_GL_NEAREST 0x2600 +#define GR_GL_LINEAR 0x2601 + +/* TextureMinFilter */ +/* GL_NEAREST */ +/* GL_LINEAR */ +#define GR_GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GR_GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GR_GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GR_GL_LINEAR_MIPMAP_LINEAR 0x2703 + +/* TextureUsage */ +#define GR_GL_FRAMEBUFFER_ATTACHMENT 0x93A3 + +/* TextureParameterName */ +#define GR_GL_TEXTURE_MAG_FILTER 0x2800 +#define GR_GL_TEXTURE_MIN_FILTER 0x2801 +#define GR_GL_TEXTURE_WRAP_S 0x2802 +#define GR_GL_TEXTURE_WRAP_T 0x2803 +#define GR_GL_TEXTURE_USAGE 0x93A2 + +/* TextureTarget */ +/* GL_TEXTURE_2D */ +#define GR_GL_TEXTURE 0x1702 +#define GR_GL_TEXTURE_CUBE_MAP 0x8513 +#define GR_GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GR_GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GR_GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GR_GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GR_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GR_GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GR_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GR_GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C + +/* TextureUnit */ +#define GR_GL_TEXTURE0 0x84C0 +#define GR_GL_TEXTURE1 0x84C1 +#define GR_GL_TEXTURE2 0x84C2 +#define GR_GL_TEXTURE3 0x84C3 +#define GR_GL_TEXTURE4 0x84C4 +#define GR_GL_TEXTURE5 0x84C5 +#define GR_GL_TEXTURE6 0x84C6 +#define GR_GL_TEXTURE7 0x84C7 +#define GR_GL_TEXTURE8 0x84C8 +#define GR_GL_TEXTURE9 0x84C9 +#define GR_GL_TEXTURE10 0x84CA +#define GR_GL_TEXTURE11 0x84CB +#define GR_GL_TEXTURE12 0x84CC +#define GR_GL_TEXTURE13 0x84CD +#define GR_GL_TEXTURE14 0x84CE +#define GR_GL_TEXTURE15 0x84CF +#define GR_GL_TEXTURE16 0x84D0 +#define GR_GL_TEXTURE17 0x84D1 +#define GR_GL_TEXTURE18 0x84D2 +#define GR_GL_TEXTURE19 0x84D3 +#define GR_GL_TEXTURE20 0x84D4 +#define GR_GL_TEXTURE21 0x84D5 +#define GR_GL_TEXTURE22 0x84D6 +#define GR_GL_TEXTURE23 0x84D7 +#define GR_GL_TEXTURE24 0x84D8 +#define GR_GL_TEXTURE25 0x84D9 +#define GR_GL_TEXTURE26 0x84DA +#define GR_GL_TEXTURE27 0x84DB +#define GR_GL_TEXTURE28 0x84DC +#define GR_GL_TEXTURE29 0x84DD +#define GR_GL_TEXTURE30 0x84DE +#define GR_GL_TEXTURE31 0x84DF +#define GR_GL_ACTIVE_TEXTURE 0x84E0 +#define GR_GL_MAX_TEXTURE_UNITS 0x84E2 + +/* TextureWrapMode */ +#define GR_GL_REPEAT 0x2901 +#define GR_GL_CLAMP_TO_EDGE 0x812F +#define GR_GL_MIRRORED_REPEAT 0x8370 + +/* Texture Swizzle */ +#define GR_GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GR_GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GR_GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GR_GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GR_GL_TEXTURE_SWIZZLE_RGBA 0x8E46 + +/* Texture mapping */ +#define GR_GL_TEXTURE_ENV 0x2300 +#define GR_GL_TEXTURE_ENV_MODE 0x2200 +#define GR_GL_TEXTURE_1D 0x0DE0 +/* GL_TEXTURE_2D */ +/* GL_TEXTURE_WRAP_S */ +/* GL_TEXTURE_WRAP_T */ +/* GL_TEXTURE_MAG_FILTER */ +/* GL_TEXTURE_MIN_FILTER */ +#define GR_GL_TEXTURE_ENV_COLOR 0x2201 +#define GR_GL_TEXTURE_GEN_S 0x0C60 +#define GR_GL_TEXTURE_GEN_T 0x0C61 +#define GR_GL_TEXTURE_GEN_MODE 0x2500 +#define GR_GL_TEXTURE_BORDER_COLOR 0x1004 +#define GR_GL_TEXTURE_WIDTH 0x1000 +#define GR_GL_TEXTURE_HEIGHT 0x1001 +#define GR_GL_TEXTURE_BORDER 0x1005 +#define GR_GL_TEXTURE_COMPONENTS 0x1003 +#define GR_GL_TEXTURE_RED_SIZE 0x805C +#define GR_GL_TEXTURE_GREEN_SIZE 0x805D +#define GR_GL_TEXTURE_BLUE_SIZE 0x805E +#define GR_GL_TEXTURE_ALPHA_SIZE 0x805F +#define GR_GL_TEXTURE_LUMINANCE_SIZE 0x8060 +#define GR_GL_TEXTURE_INTENSITY_SIZE 0x8061 +#define GR_GL_TEXTURE_INTERNAL_FORMAT 0x1003 +/* GL_NEAREST_MIPMAP_NEAREST */ +/* GL_NEAREST_MIPMAP_LINEAR */ +/* GL_LINEAR_MIPMAP_NEAREST */ +/* GL_LINEAR_MIPMAP_LINEAR */ +#define GR_GL_OBJECT_LINEAR 0x2401 +#define GR_GL_OBJECT_PLANE 0x2501 +#define GR_GL_EYE_LINEAR 0x2400 +#define GR_GL_EYE_PLANE 0x2502 +#define GR_GL_SPHERE_MAP 0x2402 +#define GR_GL_DECAL 0x2101 +#define GR_GL_MODULATE 0x2100 +/* GL_NEAREST */ +/* GL_REPEAT */ +#define GR_GL_CLAMP 0x2900 +#define GR_GL_S 0x2000 +#define GR_GL_T 0x2001 +#define GR_GL_R 0x2002 +#define GR_GL_Q 0x2003 +#define GR_GL_TEXTURE_GEN_R 0x0C62 +#define GR_GL_TEXTURE_GEN_Q 0x0C63 + +/* texture_env_combine */ +#define GR_GL_COMBINE 0x8570 +#define GR_GL_COMBINE_RGB 0x8571 +#define GR_GL_COMBINE_ALPHA 0x8572 +#define GR_GL_SOURCE0_RGB 0x8580 +#define GR_GL_SOURCE1_RGB 0x8581 +#define GR_GL_SOURCE2_RGB 0x8582 +#define GR_GL_SOURCE0_ALPHA 0x8588 +#define GR_GL_SOURCE1_ALPHA 0x8589 +#define GR_GL_SOURCE2_ALPHA 0x858A +#define GR_GL_OPERAND0_RGB 0x8590 +#define GR_GL_OPERAND1_RGB 0x8591 +#define GR_GL_OPERAND2_RGB 0x8592 +#define GR_GL_OPERAND0_ALPHA 0x8598 +#define GR_GL_OPERAND1_ALPHA 0x8599 +#define GR_GL_OPERAND2_ALPHA 0x859A +#define GR_GL_RGB_SCALE 0x8573 +#define GR_GL_ADD_SIGNED 0x8574 +#define GR_GL_INTERPOLATE 0x8575 +#define GR_GL_SUBTRACT 0x84E7 +#define GR_GL_CONSTANT 0x8576 +#define GR_GL_PRIMARY_COLOR 0x8577 +#define GR_GL_PREVIOUS 0x8578 +#define GR_GL_SRC0_RGB 0x8580 +#define GR_GL_SRC1_RGB 0x8581 +#define GR_GL_SRC2_RGB 0x8582 +#define GR_GL_SRC0_ALPHA 0x8588 +#define GR_GL_SRC1_ALPHA 0x8589 +#define GR_GL_SRC2_ALPHA 0x858A + +/* Uniform Types */ +#define GR_GL_FLOAT_VEC2 0x8B50 +#define GR_GL_FLOAT_VEC3 0x8B51 +#define GR_GL_FLOAT_VEC4 0x8B52 +#define GR_GL_INT_VEC2 0x8B53 +#define GR_GL_INT_VEC3 0x8B54 +#define GR_GL_INT_VEC4 0x8B55 +#define GR_GL_BOOL 0x8B56 +#define GR_GL_BOOL_VEC2 0x8B57 +#define GR_GL_BOOL_VEC3 0x8B58 +#define GR_GL_BOOL_VEC4 0x8B59 +#define GR_GL_FLOAT_MAT2 0x8B5A +#define GR_GL_FLOAT_MAT3 0x8B5B +#define GR_GL_FLOAT_MAT4 0x8B5C +#define GR_GL_SAMPLER_2D 0x8B5E +#define GR_GL_SAMPLER_CUBE 0x8B60 + +/* Vertex Arrays */ +#define GR_GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GR_GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GR_GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GR_GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GR_GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GR_GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GR_GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GR_GL_VERTEX_ARRAY 0x8074 +#define GR_GL_NORMAL_ARRAY 0x8075 +#define GR_GL_COLOR_ARRAY 0x8076 +#define GR_GL_INDEX_ARRAY 0x8077 +#define GR_GL_TEXTURE_COORD_ARRAY 0x8078 +#define GR_GL_EDGE_FLAG_ARRAY 0x8079 +#define GR_GL_VERTEX_ARRAY_SIZE 0x807A +#define GR_GL_VERTEX_ARRAY_TYPE 0x807B +#define GR_GL_VERTEX_ARRAY_STRIDE 0x807C +#define GR_GL_NORMAL_ARRAY_TYPE 0x807E +#define GR_GL_NORMAL_ARRAY_STRIDE 0x807F +#define GR_GL_COLOR_ARRAY_SIZE 0x8081 +#define GR_GL_COLOR_ARRAY_TYPE 0x8082 +#define GR_GL_COLOR_ARRAY_STRIDE 0x8083 +#define GR_GL_INDEX_ARRAY_TYPE 0x8085 +#define GR_GL_INDEX_ARRAY_STRIDE 0x8086 +#define GR_GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GR_GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GR_GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GR_GL_EDGE_FLAG_ARRAY_STRIDE 0x808C +#define GR_GL_VERTEX_ARRAY_POINTER 0x808E +#define GR_GL_NORMAL_ARRAY_POINTER 0x808F +#define GR_GL_COLOR_ARRAY_POINTER 0x8090 +#define GR_GL_INDEX_ARRAY_POINTER 0x8091 +#define GR_GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GR_GL_EDGE_FLAG_ARRAY_POINTER 0x8093 +#define GR_GL_V2F 0x2A20 +#define GR_GL_V3F 0x2A21 +#define GR_GL_C4UB_V2F 0x2A22 +#define GR_GL_C4UB_V3F 0x2A23 +#define GR_GL_C3F_V3F 0x2A24 +#define GR_GL_N3F_V3F 0x2A25 +#define GR_GL_C4F_N3F_V3F 0x2A26 +#define GR_GL_T2F_V3F 0x2A27 +#define GR_GL_T4F_V4F 0x2A28 +#define GR_GL_T2F_C4UB_V3F 0x2A29 +#define GR_GL_T2F_C3F_V3F 0x2A2A +#define GR_GL_T2F_N3F_V3F 0x2A2B +#define GR_GL_T2F_C4F_N3F_V3F 0x2A2C +#define GR_GL_T4F_C4F_N3F_V4F 0x2A2D + +/* Vertex Buffer Object */ +#define GR_GL_WRITE_ONLY 0x88B9 +#define GR_GL_BUFFER_MAPPED 0x88BC +/* Read Format */ +#define GR_GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GR_GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B + +/* Shader Source */ +#define GR_GL_COMPILE_STATUS 0x8B81 +#define GR_GL_INFO_LOG_LENGTH 0x8B84 +#define GR_GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GR_GL_SHADER_COMPILER 0x8DFA + +/* Shader Binary */ +#define GR_GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GR_GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 + +/* Shader Precision-Specified Types */ +#define GR_GL_LOW_FLOAT 0x8DF0 +#define GR_GL_MEDIUM_FLOAT 0x8DF1 +#define GR_GL_HIGH_FLOAT 0x8DF2 +#define GR_GL_LOW_INT 0x8DF3 +#define GR_GL_MEDIUM_INT 0x8DF4 +#define GR_GL_HIGH_INT 0x8DF5 + +/* Queries */ +#define GR_GL_QUERY_COUNTER_BITS 0x8864 +#define GR_GL_CURRENT_QUERY 0x8865 +#define GR_GL_QUERY_RESULT 0x8866 +#define GR_GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GR_GL_SAMPLES_PASSED 0x8914 +#define GR_GL_ANY_SAMPLES_PASSED 0x8C2F +#define GR_GL_TIME_ELAPSED 0x88BF +#define GR_GL_TIMESTAMP 0x8E28 +#define GR_GL_PRIMITIVES_GENERATED 0x8C87 +#define GR_GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 + + +/* Framebuffer Object. */ +#define GR_GL_FRAMEBUFFER 0x8D40 +#define GR_GL_READ_FRAMEBUFFER 0x8CA8 +#define GR_GL_DRAW_FRAMEBUFFER 0x8CA9 + +#define GR_GL_RENDERBUFFER 0x8D41 + +#define GR_GL_RGBA4 0x8056 +#define GR_GL_RGB5_A1 0x8057 +#define GR_GL_RGB565 0x8D62 +#define GR_GL_RGBA8 0x8058 +#define GR_GL_RGB8 0x8051 +#define GR_GL_BGRA8 0x93A1 +#define GR_GL_SRGB 0x8C40 +#define GR_GL_SRGB8 0x8C41 +#define GR_GL_SRGB_ALPHA 0x8C42 +#define GR_GL_SRGB8_ALPHA8 0x8C43 +#define GR_GL_DEPTH_COMPONENT16 0x81A5 +#define GR_GL_STENCIL_INDEX 0x1901 +#define GR_GL_STENCIL_INDEX4 0x8D47 +#define GR_GL_STENCIL_INDEX8 0x8D48 +#define GR_GL_STENCIL_INDEX16 0x8D49 +#define GR_GL_DEPTH_STENCIL 0x84F9 +#define GR_GL_DEPTH24_STENCIL8 0x88F0 + +#define GR_GL_MAX_SAMPLES 0x8D57 + +#define GR_GL_RENDERBUFFER_WIDTH 0x8D42 +#define GR_GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GR_GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GR_GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GR_GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GR_GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GR_GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GR_GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GR_GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 + +#define GR_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GR_GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 + +#define GR_GL_COLOR_ATTACHMENT0 0x8CE0 +#define GR_GL_DEPTH_ATTACHMENT 0x8D00 +#define GR_GL_STENCIL_ATTACHMENT 0x8D20 +#define GR_GL_DEPTH_STENCIL_ATTACHMENT 0x821A + +#define GR_GL_NONE 0 + +#define GR_GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GR_GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GR_GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GR_GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 +#define GR_GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD + +#define GR_GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GR_GL_RENDERBUFFER_BINDING 0x8CA7 +#define GR_GL_MAX_RENDERBUFFER_SIZE 0x84E8 + +#define GR_GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 + +#endif diff --git a/include/gpu/GrGLInterface.h b/include/gpu/GrGLInterface.h new file mode 100644 index 0000000..716cff9 --- /dev/null +++ b/include/gpu/GrGLInterface.h @@ -0,0 +1,418 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrGLInterface_DEFINED +#define GrGLInterface_DEFINED + +#include "GrGLConfig.h" +#include "GrRefCnt.h" + +#if !defined(GR_GL_FUNCTION_TYPE) + #define GR_GL_FUNCTION_TYPE +#endif + +//////////////////////////////////////////////////////////////////////////////// + +/** + * Helpers for glGetString() + */ + +typedef uint32_t GrGLVersion; +typedef uint32_t GrGLSLVersion; + +#define GR_GL_VER(major, minor) ((static_cast<int>(major) << 16) | \ + static_cast<int>(minor)) +#define GR_GLSL_VER(major, minor) ((static_cast<int>(major) << 16) | \ + static_cast<int>(minor)) + +// these variants assume caller already has a string from glGetString() +GrGLVersion GrGLGetVersionFromString(const char* versionString); +GrGLSLVersion GrGLGetGLSLVersionFromString(const char* versionString); +bool GrGLHasExtensionFromString(const char* ext, const char* extensionString); + +// these variants call glGetString() +bool GrGLHasExtension(const GrGLInterface*, const char* ext); +GrGLVersion GrGLGetVersion(const GrGLInterface*); +GrGLSLVersion GrGLGetGLSLVersion(const GrGLInterface*); + +//////////////////////////////////////////////////////////////////////////////// + +/** + * Rather than depend on platform-specific GL headers and libraries, we require + * the client to provide a struct of GL function pointers. This struct can be + * specified per-GrContext as a parameter to GrContext::Create. If NULL is + * passed to Create then the "default" GL interface is used. If the default is + * also NULL GrContext creation will fail. + * + * The default interface is returned by GrGLDefaultInterface. This function's + * implementation is platform-specifc. Several have been provided, along with an + * implementation that simply returns NULL. It is implementation-specific + * whether the same GrGLInterface is returned or whether a new one is created + * at each call. Some platforms may not be able to use a single GrGLInterface + * because extension function ptrs vary across contexts. Note that GrGLInterface + * is ref-counted. So if the same object is returned by multiple calls to + * GrGLDefaultInterface, each should bump the ref count. + * + * By defining GR_GL_PER_GL_CALL_IFACE_CALLBACK to 1 the client can specify a + * callback function that will be called prior to each GL function call. See + * comments in GrGLConfig.h + */ + +struct GrGLInterface; + +const GrGLInterface* GrGLDefaultInterface(); + +/** + * Creates a GrGLInterface for a "native" GL context (e.g. WGL on windows, + * GLX on linux, AGL on Mac). On platforms that have context-specific function + * pointers for GL extensions (e.g. windows) the returned interface is only + * valid for the context that was current at creation. + */ +const GrGLInterface* GrGLCreateNativeInterface(); + +/** + * Creates a GrGLInterface for an OSMesa context. + */ +const GrGLInterface* GrGLCreateMesaInterface(); + +/** + * Creates a null GrGLInterface that doesn't draw anything. Used for measuring + * CPU overhead. + */ +const GrGLInterface* GrGLCreateNullInterface(); + +typedef unsigned int GrGLenum; +typedef unsigned char GrGLboolean; +typedef unsigned int GrGLbitfield; +typedef signed char GrGLbyte; +typedef char GrGLchar; +typedef short GrGLshort; +typedef int GrGLint; +typedef int GrGLsizei; +typedef int64_t GrGLint64; +typedef unsigned char GrGLubyte; +typedef unsigned short GrGLushort; +typedef unsigned int GrGLuint; +typedef uint64_t GrGLuint64; +typedef float GrGLfloat; +typedef float GrGLclampf; +typedef double GrGLdouble; +typedef double GrGLclampd; +typedef void GrGLvoid; +typedef long GrGLintptr; +typedef long GrGLsizeiptr; + +enum GrGLBinding { + kDesktop_GrGLBinding = 0x01, + kES2_GrGLBinding = 0x02 +}; + +extern "C" { + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLActiveTextureProc)(GrGLenum texture); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLAttachShaderProc)(GrGLuint program, GrGLuint shader); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBeginQueryProc)(GrGLenum target, GrGLuint id); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindAttribLocationProc)(GrGLuint program, GrGLuint index, const char* name); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindBufferProc)(GrGLenum target, GrGLuint buffer); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindTextureProc)(GrGLenum target, GrGLuint texture); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlendColorProc)(GrGLclampf red, GrGLclampf green, GrGLclampf blue, GrGLclampf alpha); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindFragDataLocationProc)(GrGLuint program, GrGLuint colorNumber, const GrGLchar* name); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlendFuncProc)(GrGLenum sfactor, GrGLenum dfactor); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBufferDataProc)(GrGLenum target, GrGLsizeiptr size, const GrGLvoid* data, GrGLenum usage); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBufferSubDataProc)(GrGLenum target, GrGLintptr offset, GrGLsizeiptr size, const GrGLvoid* data); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClearProc)(GrGLbitfield mask); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClearColorProc)(GrGLclampf red, GrGLclampf green, GrGLclampf blue, GrGLclampf alpha); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClearStencilProc)(GrGLint s); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLColorMaskProc)(GrGLboolean red, GrGLboolean green, GrGLboolean blue, GrGLboolean alpha); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLColorPointerProc)(GrGLint size, GrGLenum type, GrGLsizei stride, const GrGLvoid* pointer); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCompileShaderProc)(GrGLuint shader); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCompressedTexImage2DProc)(GrGLenum target, GrGLint level, GrGLenum internalformat, GrGLsizei width, GrGLsizei height, GrGLint border, GrGLsizei imageSize, const GrGLvoid* data); + typedef GrGLuint (GR_GL_FUNCTION_TYPE *GrGLCreateProgramProc)(void); + typedef GrGLuint (GR_GL_FUNCTION_TYPE *GrGLCreateShaderProc)(GrGLenum type); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCullFaceProc)(GrGLenum mode); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteBuffersProc)(GrGLsizei n, const GrGLuint* buffers); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteProgramProc)(GrGLuint program); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteQueriesProc)(GrGLsizei n, const GrGLuint *ids); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteShaderProc)(GrGLuint shader); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteTexturesProc)(GrGLsizei n, const GrGLuint* textures); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDepthMaskProc)(GrGLboolean flag); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDisableProc)(GrGLenum cap); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDisableVertexAttribArrayProc)(GrGLuint index); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDrawArraysProc)(GrGLenum mode, GrGLint first, GrGLsizei count); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDrawBufferProc)(GrGLenum mode); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDrawBuffersProc)(GrGLsizei n, const GrGLenum* bufs); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDrawElementsProc)(GrGLenum mode, GrGLsizei count, GrGLenum type, const GrGLvoid* indices); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLEnableProc)(GrGLenum cap); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLEnableVertexAttribArrayProc)(GrGLuint index); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLEndQueryProc)(GrGLenum target); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFinishProc)(); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFlushProc)(); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFrontFaceProc)(GrGLenum mode); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenBuffersProc)(GrGLsizei n, GrGLuint* buffers); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenQueriesProc)(GrGLsizei n, GrGLuint *ids); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenTexturesProc)(GrGLsizei n, GrGLuint* textures); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetBufferParameterivProc)(GrGLenum target, GrGLenum pname, GrGLint* params); + typedef GrGLenum (GR_GL_FUNCTION_TYPE *GrGLGetErrorProc)(); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetIntegervProc)(GrGLenum pname, GrGLint* params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetProgramInfoLogProc)(GrGLuint program, GrGLsizei bufsize, GrGLsizei* length, char* infolog); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetProgramivProc)(GrGLuint program, GrGLenum pname, GrGLint* params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetQueryivProc)(GrGLenum GLtarget, GrGLenum pname, GrGLint *params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetQueryObjecti64vProc)(GrGLuint id, GrGLenum pname, GrGLint64 *params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetQueryObjectivProc)(GrGLuint id, GrGLenum pname, GrGLint *params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetQueryObjectui64vProc)(GrGLuint id, GrGLenum pname, GrGLuint64 *params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetQueryObjectuivProc)(GrGLuint id, GrGLenum pname, GrGLuint *params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetShaderInfoLogProc)(GrGLuint shader, GrGLsizei bufsize, GrGLsizei* length, char* infolog); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetShaderivProc)(GrGLuint shader, GrGLenum pname, GrGLint* params); + typedef const GrGLubyte* (GR_GL_FUNCTION_TYPE *GrGLGetStringProc)(GrGLenum name); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetTexLevelParameterivProc)(GrGLenum target, GrGLint level, GrGLenum pname, GrGLint* params); + typedef GrGLint (GR_GL_FUNCTION_TYPE *GrGLGetUniformLocationProc)(GrGLuint program, const char* name); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLLineWidthProc)(GrGLfloat width); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLLinkProgramProc)(GrGLuint program); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLPixelStoreiProc)(GrGLenum pname, GrGLint param); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLQueryCounterProc)(GrGLuint id, GrGLenum target); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLReadBufferProc)(GrGLenum src); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLReadPixelsProc)(GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height, GrGLenum format, GrGLenum type, GrGLvoid* pixels); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLScissorProc)(GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLShaderSourceProc)(GrGLuint shader, GrGLsizei count, const char** str, const GrGLint* length); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilFuncProc)(GrGLenum func, GrGLint ref, GrGLuint mask); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilFuncSeparateProc)(GrGLenum face, GrGLenum func, GrGLint ref, GrGLuint mask); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilMaskProc)(GrGLuint mask); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilMaskSeparateProc)(GrGLenum face, GrGLuint mask); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilOpProc)(GrGLenum fail, GrGLenum zfail, GrGLenum zpass); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilOpSeparateProc)(GrGLenum face, GrGLenum fail, GrGLenum zfail, GrGLenum zpass); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexImage2DProc)(GrGLenum target, GrGLint level, GrGLint internalformat, GrGLsizei width, GrGLsizei height, GrGLint border, GrGLenum format, GrGLenum type, const GrGLvoid* pixels); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexParameteriProc)(GrGLenum target, GrGLenum pname, GrGLint param); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexStorage2DProc)(GrGLenum target, GrGLsizei levels, GrGLenum internalformat, GrGLsizei width, GrGLsizei height); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexSubImage2DProc)(GrGLenum target, GrGLint level, GrGLint xoffset, GrGLint yoffset, GrGLsizei width, GrGLsizei height, GrGLenum format, GrGLenum type, const GrGLvoid* pixels); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1fProc)(GrGLint location, GrGLfloat v0); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1iProc)(GrGLint location, GrGLint v0); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2fProc)(GrGLint location, GrGLfloat v0, GrGLfloat v1); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2iProc)(GrGLint location, GrGLint v0, GrGLint v1); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3fProc)(GrGLint location, GrGLfloat v0, GrGLfloat v1, GrGLfloat v2); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3iProc)(GrGLint location, GrGLint v0, GrGLint v1, GrGLint v2); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4fProc)(GrGLint location, GrGLfloat v0, GrGLfloat v1, GrGLfloat v2, GrGLfloat v3); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4iProc)(GrGLint location, GrGLint v0, GrGLint v1, GrGLint v2, GrGLint v3); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix2fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix3fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix4fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUseProgramProc)(GrGLuint program); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib4fvProc)(GrGLuint indx, const GrGLfloat* values); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttribPointerProc)(GrGLuint indx, GrGLint size, GrGLenum type, GrGLboolean normalized, GrGLsizei stride, const GrGLvoid* ptr); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLViewportProc)(GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height); + + // FBO Extension Functions + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindFramebufferProc)(GrGLenum target, GrGLuint framebuffer); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindRenderbufferProc)(GrGLenum target, GrGLuint renderbuffer); + typedef GrGLenum (GR_GL_FUNCTION_TYPE *GrGLCheckFramebufferStatusProc)(GrGLenum target); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteFramebuffersProc)(GrGLsizei n, const GrGLuint *framebuffers); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteRenderbuffersProc)(GrGLsizei n, const GrGLuint *renderbuffers); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFramebufferRenderbufferProc)(GrGLenum target, GrGLenum attachment, GrGLenum renderbuffertarget, GrGLuint renderbuffer); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFramebufferTexture2DProc)(GrGLenum target, GrGLenum attachment, GrGLenum textarget, GrGLuint texture, GrGLint level); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenFramebuffersProc)(GrGLsizei n, GrGLuint *framebuffers); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenRenderbuffersProc)(GrGLsizei n, GrGLuint *renderbuffers); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetFramebufferAttachmentParameterivProc)(GrGLenum target, GrGLenum attachment, GrGLenum pname, GrGLint* params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetRenderbufferParameterivProc)(GrGLenum target, GrGLenum pname, GrGLint* params); + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLRenderbufferStorageProc)(GrGLenum target, GrGLenum internalformat, GrGLsizei width, GrGLsizei height); + + // Multisampling Extension Functions + // same prototype for ARB_FBO, EXT_FBO, GL 3.0, & Apple ES extension + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLRenderbufferStorageMultisampleProc)(GrGLenum target, GrGLsizei samples, GrGLenum internalformat, GrGLsizei width, GrGLsizei height); + // desktop: ext_fbo_blit, arb_fbo, gl 3.0 + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlitFramebufferProc)(GrGLint srcX0, GrGLint srcY0, GrGLint srcX1, GrGLint srcY1, GrGLint dstX0, GrGLint dstY0, GrGLint dstX1, GrGLint dstY1, GrGLbitfield mask, GrGLenum filter); + // apple's es extension + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLResolveMultisampleFramebufferProc)(); + + // Buffer mapping (extension in ES). + typedef GrGLvoid* (GR_GL_FUNCTION_TYPE *GrGLMapBufferProc)(GrGLenum target, GrGLenum access); + typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLUnmapBufferProc)(GrGLenum target); + + // Dual source blending + typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindFragDataLocationIndexedProc)(GrGLuint program, GrGLuint colorNumber, GrGLuint index, const GrGLchar * name); +} // extern "C" + +#if GR_GL_PER_GL_FUNC_CALLBACK +typedef void (*GrGLInterfaceCallbackProc)(const GrGLInterface*); +typedef intptr_t GrGLInterfaceCallbackData; +#endif + + +enum GrGLCapability { + kProbe_GrGLCapability = -1 +}; + +/* + * The following interface exports the OpenGL entry points used by the system. + * Use of OpenGL calls is disallowed. All calls should be invoked through + * the global instance of this struct, defined above. + * + * IMPORTANT NOTE: The OpenGL entry points exposed here include both core GL + * functions, and extensions. The system assumes that the address of the + * extension pointer will be valid across contexts. + */ +struct GR_API GrGLInterface : public GrRefCnt { + + GrGLInterface(); + + bool validate() const; + bool supportsDesktop() const { + return 0 != (kDesktop_GrGLBinding & fBindingsExported); + } + bool supportsES2() const { + return 0 != (kES2_GrGLBinding & fBindingsExported); + } + + // Indicator variable specifying the type of GL implementation + // exported: GLES{1|2} or Desktop. + GrGLBinding fBindingsExported; + + GrGLActiveTextureProc fActiveTexture; + GrGLAttachShaderProc fAttachShader; + GrGLBeginQueryProc fBeginQuery; + GrGLBindAttribLocationProc fBindAttribLocation; + GrGLBindBufferProc fBindBuffer; + GrGLBindFragDataLocationProc fBindFragDataLocation; + GrGLBindTextureProc fBindTexture; + GrGLBlendColorProc fBlendColor; + GrGLBlendFuncProc fBlendFunc; + GrGLBufferDataProc fBufferData; + GrGLBufferSubDataProc fBufferSubData; + GrGLClearProc fClear; + GrGLClearColorProc fClearColor; + GrGLClearStencilProc fClearStencil; + GrGLColorMaskProc fColorMask; + GrGLColorPointerProc fColorPointer; + GrGLCompileShaderProc fCompileShader; + GrGLCompressedTexImage2DProc fCompressedTexImage2D; + GrGLCreateProgramProc fCreateProgram; + GrGLCreateShaderProc fCreateShader; + GrGLCullFaceProc fCullFace; + GrGLDeleteBuffersProc fDeleteBuffers; + GrGLDeleteProgramProc fDeleteProgram; + GrGLDeleteQueriesProc fDeleteQueries; + GrGLDeleteShaderProc fDeleteShader; + GrGLDeleteTexturesProc fDeleteTextures; + GrGLDepthMaskProc fDepthMask; + GrGLDisableProc fDisable; + GrGLDisableVertexAttribArrayProc fDisableVertexAttribArray; + GrGLDrawArraysProc fDrawArrays; + GrGLDrawBufferProc fDrawBuffer; + GrGLDrawBuffersProc fDrawBuffers; + GrGLDrawElementsProc fDrawElements; + GrGLEnableProc fEnable; + GrGLEnableVertexAttribArrayProc fEnableVertexAttribArray; + GrGLEndQueryProc fEndQuery; + GrGLFinishProc fFinish; + GrGLFlushProc fFlush; + GrGLFrontFaceProc fFrontFace; + GrGLGenBuffersProc fGenBuffers; + GrGLGenQueriesProc fGenQueries; + GrGLGenTexturesProc fGenTextures; + GrGLGetBufferParameterivProc fGetBufferParameteriv; + GrGLGetErrorProc fGetError; + GrGLGetIntegervProc fGetIntegerv; + GrGLGetQueryObjecti64vProc fGetQueryObjecti64v; + GrGLGetQueryObjectivProc fGetQueryObjectiv; + GrGLGetQueryObjectui64vProc fGetQueryObjectui64v; + GrGLGetQueryObjectuivProc fGetQueryObjectuiv; + GrGLGetQueryivProc fGetQueryiv; + GrGLGetProgramInfoLogProc fGetProgramInfoLog; + GrGLGetProgramivProc fGetProgramiv; + GrGLGetShaderInfoLogProc fGetShaderInfoLog; + GrGLGetShaderivProc fGetShaderiv; + GrGLGetStringProc fGetString; + GrGLGetTexLevelParameterivProc fGetTexLevelParameteriv; + GrGLGetUniformLocationProc fGetUniformLocation; + GrGLLineWidthProc fLineWidth; + GrGLLinkProgramProc fLinkProgram; + GrGLPixelStoreiProc fPixelStorei; + GrGLQueryCounterProc fQueryCounter; + GrGLReadBufferProc fReadBuffer; + GrGLReadPixelsProc fReadPixels; + GrGLScissorProc fScissor; + GrGLShaderSourceProc fShaderSource; + GrGLStencilFuncProc fStencilFunc; + GrGLStencilFuncSeparateProc fStencilFuncSeparate; + GrGLStencilMaskProc fStencilMask; + GrGLStencilMaskSeparateProc fStencilMaskSeparate; + GrGLStencilOpProc fStencilOp; + GrGLStencilOpSeparateProc fStencilOpSeparate; + GrGLTexImage2DProc fTexImage2D; + GrGLTexParameteriProc fTexParameteri; + GrGLTexSubImage2DProc fTexSubImage2D; + GrGLTexStorage2DProc fTexStorage2D; + GrGLUniform1fProc fUniform1f; + GrGLUniform1iProc fUniform1i; + GrGLUniform1fvProc fUniform1fv; + GrGLUniform1ivProc fUniform1iv; + GrGLUniform2fProc fUniform2f; + GrGLUniform2iProc fUniform2i; + GrGLUniform2fvProc fUniform2fv; + GrGLUniform2ivProc fUniform2iv; + GrGLUniform3fProc fUniform3f; + GrGLUniform3iProc fUniform3i; + GrGLUniform3fvProc fUniform3fv; + GrGLUniform3ivProc fUniform3iv; + GrGLUniform4fProc fUniform4f; + GrGLUniform4iProc fUniform4i; + GrGLUniform4fvProc fUniform4fv; + GrGLUniform4ivProc fUniform4iv; + GrGLUniformMatrix2fvProc fUniformMatrix2fv; + GrGLUniformMatrix3fvProc fUniformMatrix3fv; + GrGLUniformMatrix4fvProc fUniformMatrix4fv; + GrGLUseProgramProc fUseProgram; + GrGLVertexAttrib4fvProc fVertexAttrib4fv; + GrGLVertexAttribPointerProc fVertexAttribPointer; + GrGLViewportProc fViewport; + + // FBO Extension Functions + GrGLBindFramebufferProc fBindFramebuffer; + GrGLBindRenderbufferProc fBindRenderbuffer; + GrGLCheckFramebufferStatusProc fCheckFramebufferStatus; + GrGLDeleteFramebuffersProc fDeleteFramebuffers; + GrGLDeleteRenderbuffersProc fDeleteRenderbuffers; + GrGLFramebufferRenderbufferProc fFramebufferRenderbuffer; + GrGLFramebufferTexture2DProc fFramebufferTexture2D; + GrGLGenFramebuffersProc fGenFramebuffers; + GrGLGenRenderbuffersProc fGenRenderbuffers; + GrGLGetFramebufferAttachmentParameterivProc fGetFramebufferAttachmentParameteriv; + GrGLGetRenderbufferParameterivProc fGetRenderbufferParameteriv; + GrGLRenderbufferStorageProc fRenderbufferStorage; + + // Multisampling Extension Functions + // same prototype for ARB_FBO, EXT_FBO, GL 3.0, & Apple ES extension + GrGLRenderbufferStorageMultisampleProc fRenderbufferStorageMultisample; + // desktop: ext_fbo_blit, arb_fbo, gl 3.0 + GrGLBlitFramebufferProc fBlitFramebuffer; + // apple's es extension + GrGLResolveMultisampleFramebufferProc fResolveMultisampleFramebuffer; + + // Buffer mapping (extension in ES). + GrGLMapBufferProc fMapBuffer; + GrGLUnmapBufferProc fUnmapBuffer; + + // Dual Source Blending + GrGLBindFragDataLocationIndexedProc fBindFragDataLocationIndexed; + + // Per-GL func callback +#if GR_GL_PER_GL_FUNC_CALLBACK + GrGLInterfaceCallbackProc fCallback; + GrGLInterfaceCallbackData fCallbackData; +#endif + +}; + +#endif diff --git a/include/gpu/GrGlyph.h b/include/gpu/GrGlyph.h new file mode 100644 index 0000000..a0d81a1 --- /dev/null +++ b/include/gpu/GrGlyph.h @@ -0,0 +1,82 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrGlyph_DEFINED +#define GrGlyph_DEFINED + +#include "GrPath.h" +#include "GrRect.h" + +class GrAtlas; + +/* Need this to be quad-state: + - complete w/ image + - just metrics + - failed to get image, but has metrics + - failed to get metrics + */ +struct GrGlyph { + typedef uint32_t PackedID; + + GrAtlas* fAtlas; + GrPath* fPath; + PackedID fPackedID; + GrIRect16 fBounds; + GrIPoint16 fAtlasLocation; + + void init(GrGlyph::PackedID packed, const GrIRect& bounds) { + fAtlas = NULL; + fPath = NULL; + fPackedID = packed; + fBounds.set(bounds); + fAtlasLocation.set(0, 0); + } + + void free() { + if (fPath) { + delete fPath; + fPath = NULL; + } + } + + int width() const { return fBounds.width(); } + int height() const { return fBounds.height(); } + bool isEmpty() const { return fBounds.isEmpty(); } + uint16_t glyphID() const { return UnpackID(fPackedID); } + + /////////////////////////////////////////////////////////////////////////// + + static inline unsigned ExtractSubPixelBitsFromFixed(GrFixed pos) { + // two most significant fraction bits from fixed-point + return (pos >> 14) & 3; + } + + static inline PackedID Pack(uint16_t glyphID, GrFixed x, GrFixed y) { + x = ExtractSubPixelBitsFromFixed(x); + y = ExtractSubPixelBitsFromFixed(y); + return (x << 18) | (y << 16) | glyphID; + } + + static inline GrFixed UnpackFixedX(PackedID packed) { + return ((packed >> 18) & 3) << 14; + } + + static inline GrFixed UnpackFixedY(PackedID packed) { + return ((packed >> 16) & 3) << 14; + } + + static inline uint16_t UnpackID(PackedID packed) { + return (uint16_t)packed; + } +}; + + +#endif + diff --git a/include/gpu/GrInstanceCounter.h b/include/gpu/GrInstanceCounter.h new file mode 100644 index 0000000..b3e21d2 --- /dev/null +++ b/include/gpu/GrInstanceCounter.h @@ -0,0 +1,40 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrInstanceCounter_DEFINED +#define GrInstanceCounter_DEFINED + +#include "GrTypes.h" + +template <typename T> class GrInstanceCounter { +public: + GrInstanceCounter() { + ++gCounter; + GrPrintf("+ %s %d\n", T::InstanceCounterClassName(), gCounter); + } + + ~GrInstanceCounter() { + --gCounter; + GrPrintf("- %s %d\n", T::InstanceCounterClassName(), gCounter); + } + +private: + static int gCounter; +}; + +template <typename T> int GrInstanceCounter<T>::gCounter; + +#define DECLARE_INSTANCE_COUNTER(T) \ + static const char* InstanceCounterClassName() { return #T; } \ + friend class GrInstanceCounter<T>; \ + GrInstanceCounter<T> fInstanceCounter + +#endif + diff --git a/include/gpu/GrKey.h b/include/gpu/GrKey.h new file mode 100644 index 0000000..813d82d --- /dev/null +++ b/include/gpu/GrKey.h @@ -0,0 +1,40 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrKey_DEFINED +#define GrKey_DEFINED + +#include "GrRefCnt.h" + +class GrKey : public GrRefCnt { +public: + typedef intptr_t Hash; + + explicit GrKey(Hash hash) : fHash(hash) {} + + intptr_t getHash() const { return fHash; } + + bool operator<(const GrKey& rh) const { + return fHash < rh.fHash || (fHash == rh.fHash && this->lt(rh)); + } + bool operator==(const GrKey& rh) const { + return fHash == rh.fHash && this->eq(rh); + } + +protected: + virtual bool lt(const GrKey& rh) const = 0; + virtual bool eq(const GrKey& rh) const = 0; + +private: + const Hash fHash; +}; + +#endif + diff --git a/include/gpu/GrMatrix.h b/include/gpu/GrMatrix.h new file mode 100644 index 0000000..055680a --- /dev/null +++ b/include/gpu/GrMatrix.h @@ -0,0 +1,19 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrMatrix_DEFINED +#define GrMatrix_DEFINED + +#include "GrRect.h" +#include "SkMatrix.h" + +typedef SkMatrix GrMatrix; + +#endif diff --git a/include/gpu/GrNoncopyable.h b/include/gpu/GrNoncopyable.h new file mode 100644 index 0000000..cad722f --- /dev/null +++ b/include/gpu/GrNoncopyable.h @@ -0,0 +1,31 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrNoncopyable_DEFINED +#define GrNoncopyable_DEFINED + +#include "GrTypes.h" + +/** + * Base for classes that want to disallow copying themselves. It makes its + * copy-constructor and assignment operators private (and unimplemented). + */ +class GR_API GrNoncopyable { +public: + GrNoncopyable() {} + +private: + // illegal + GrNoncopyable(const GrNoncopyable&); + GrNoncopyable& operator=(const GrNoncopyable&); +}; + +#endif + diff --git a/include/gpu/GrPaint.h b/include/gpu/GrPaint.h new file mode 100644 index 0000000..f1d74b2 --- /dev/null +++ b/include/gpu/GrPaint.h @@ -0,0 +1,260 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef GrPaint_DEFINED +#define GrPaint_DEFINED + +#include "GrTexture.h" +#include "GrColor.h" +#include "GrSamplerState.h" + +#include "SkXfermode.h" + +/** + * The paint describes how pixels are colored when the context draws to + * them. TODO: Make this a "real" class with getters and setters, default + * values, and documentation. + */ +class GrPaint { +public: + enum { + kMaxTextures = 1, + kMaxMasks = 1, + }; + + // All the paint fields are public except textures/samplers + GrBlendCoeff fSrcBlendCoeff; + GrBlendCoeff fDstBlendCoeff; + bool fAntiAlias; + bool fDither; + bool fColorMatrixEnabled; + + GrColor fColor; + + GrColor fColorFilterColor; + SkXfermode::Mode fColorFilterXfermode; + float fColorMatrix[20]; + + void setTexture(int i, GrTexture* texture) { + GrAssert((unsigned)i < kMaxTextures); + GrSafeRef(texture); + GrSafeUnref(fTextures[i]); + fTextures[i] = texture; + } + + GrTexture* getTexture(int i) const { + GrAssert((unsigned)i < kMaxTextures); + return fTextures[i]; + } + + GrSamplerState* textureSampler(int i) { + GrAssert((unsigned)i < kMaxTextures); + return fTextureSamplers + i; + } + + const GrSamplerState& getTextureSampler(int i) const { + GrAssert((unsigned)i < kMaxTextures); + return fTextureSamplers[i]; + } + + // The mask can be alpha-only or per channel. It is applied + // after the colorfilter + void setMask(int i, GrTexture* mask) { + GrAssert((unsigned)i < kMaxMasks); + GrSafeRef(mask); + GrSafeUnref(fMaskTextures[i]); + fMaskTextures[i] = mask; + } + + GrTexture* getMask(int i) const { + GrAssert((unsigned)i < kMaxMasks); + return fMaskTextures[i]; + } + + // mask's sampler matrix is always applied to the positions + // (i.e. no explicit texture coordinates) + GrSamplerState* maskSampler(int i) { + GrAssert((unsigned)i < kMaxMasks); + return fMaskSamplers + i; + } + + const GrSamplerState& getMaskSampler(int i) const { + GrAssert((unsigned)i < kMaxMasks); + return fMaskSamplers[i]; + } + + // pre-concats sampler matrices for non-NULL textures and masks + void preConcatActiveSamplerMatrices(const GrMatrix& matrix) { + for (int i = 0; i < kMaxTextures; ++i) { + fTextureSamplers[i].preConcatMatrix(matrix); + } + for (int i = 0; i < kMaxMasks; ++i) { + fMaskSamplers[i].preConcatMatrix(matrix); + } + } + + // uninitialized + GrPaint() { + for (int i = 0; i < kMaxTextures; ++i) { + fTextures[i] = NULL; + } + for (int i = 0; i < kMaxMasks; ++i) { + fMaskTextures[i] = NULL; + } + } + + GrPaint(const GrPaint& paint) { + for (int i = 0; i < kMaxTextures; ++i) { + fTextures[i] = NULL; + } + for (int i = 0; i < kMaxMasks; ++i) { + fMaskTextures[i] = NULL; + } + *this = paint; + } + + GrPaint& operator=(const GrPaint& paint) { + fSrcBlendCoeff = paint.fSrcBlendCoeff; + fDstBlendCoeff = paint.fDstBlendCoeff; + fAntiAlias = paint.fAntiAlias; + fDither = paint.fDither; + + fColor = paint.fColor; + + fColorFilterColor = paint.fColorFilterColor; + fColorFilterXfermode = paint.fColorFilterXfermode; + memcpy(fColorMatrix, paint.fColorMatrix, sizeof(fColorMatrix)); + fColorMatrixEnabled = paint.fColorMatrixEnabled; + + for (int i = 0; i < kMaxTextures; ++i) { + GrSafeUnref(fTextures[i]); + fTextureSamplers[i] = paint.fTextureSamplers[i]; + fTextures[i] = paint.fTextures[i]; + GrSafeRef(fTextures[i]); + } + for (int i = 0; i < kMaxMasks; ++i) { + GrSafeUnref(fMaskTextures[i]); + fMaskSamplers[i] = paint.fMaskSamplers[i]; + fMaskTextures[i] = paint.fMaskTextures[i]; + GrSafeRef(fMaskTextures[i]); + } + return *this; + } + + ~GrPaint() { + for (int i = 0; i < kMaxTextures; ++i) { + GrSafeUnref(fTextures[i]); + } + for (int i = 0; i < kMaxMasks; ++i) { + GrSafeUnref(fMaskTextures[i]); + } + } + + // sets paint to src-over, solid white, no texture, no mask + void reset() { + this->resetBlend(); + this->resetOptions(); + this->resetColor(); + this->resetTextures(); + this->resetColorFilter(); + this->resetMasks(); + } + + void resetColorFilter() { + fColorFilterXfermode = SkXfermode::kDst_Mode; + fColorFilterColor = GrColorPackRGBA(0xff, 0xff, 0xff, 0xff); + memset(fColorMatrix, 0, sizeof(fColorMatrix)); + fColorMatrixEnabled = false; + } + + bool hasTexture() const { + return 0 != this->getActiveTextureStageMask(); + } + + bool hasMask() const { + return 0 != this->getActiveMaskStageMask(); + } + + bool hasTextureOrMask() const { + return this->hasTexture() || this->hasMask(); + } + + // helpers for GrContext, GrTextContext + int getActiveTextureStageMask() const { + int mask = 0; + for (int i = 0; i < kMaxTextures; ++i) { + if (NULL != fTextures[i]) { + mask |= 1 << (i + kFirstTextureStage); + } + } + return mask; + } + + int getActiveMaskStageMask() const { + int mask = 0; + for (int i = 0; i < kMaxMasks; ++i) { + if (NULL != fMaskTextures[i]) { + mask |= 1 << (i + kFirstMaskStage); + } + } + return mask; + } + + int getActiveStageMask() const { + return this->getActiveTextureStageMask() | + this->getActiveMaskStageMask(); + } + + // internal use + // GrPaint's textures and masks map to the first N stages + // of GrDrawTarget in that order (textures followed by masks) + enum { + kFirstTextureStage = 0, + kFirstMaskStage = kMaxTextures, + kTotalStages = kMaxTextures + kMaxMasks, + }; + +private: + + GrSamplerState fTextureSamplers[kMaxTextures]; + GrSamplerState fMaskSamplers[kMaxMasks]; + + GrTexture* fTextures[kMaxTextures]; + GrTexture* fMaskTextures[kMaxMasks]; + + void resetBlend() { + fSrcBlendCoeff = kOne_BlendCoeff; + fDstBlendCoeff = kZero_BlendCoeff; + } + + void resetOptions() { + fAntiAlias = false; + fDither = false; + } + + void resetColor() { + fColor = GrColorPackRGBA(0xff, 0xff, 0xff, 0xff); + } + + void resetTextures() { + for (int i = 0; i < kMaxTextures; ++i) { + this->setTexture(i, NULL); + fTextureSamplers[i].reset(); + } + } + + void resetMasks() { + for (int i = 0; i < kMaxMasks; ++i) { + this->setMask(i, NULL); + fMaskSamplers[i].reset(); + } + } +}; + +#endif diff --git a/include/gpu/GrPath.h b/include/gpu/GrPath.h new file mode 100644 index 0000000..7da0d48 --- /dev/null +++ b/include/gpu/GrPath.h @@ -0,0 +1,20 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrPath_DEFINED +#define GrPath_DEFINED + +#include "GrTypes.h" +#include "SkPath.h" + +typedef SkPath GrPath; + +#endif + diff --git a/include/gpu/GrPoint.h b/include/gpu/GrPoint.h new file mode 100644 index 0000000..b32123b --- /dev/null +++ b/include/gpu/GrPoint.h @@ -0,0 +1,31 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrPoint_DEFINED +#define GrPoint_DEFINED + +#include "GrTypes.h" +#include "GrScalar.h" +#include "SkPoint.h" + +#define GrPoint SkPoint +#define GrVec SkVector + +struct GrIPoint16 { + int16_t fX, fY; + + void set(intptr_t x, intptr_t y) { + fX = GrToS16(x); + fY = GrToS16(y); + } +}; + +#endif + diff --git a/include/gpu/GrRect.h b/include/gpu/GrRect.h new file mode 100644 index 0000000..60a4773 --- /dev/null +++ b/include/gpu/GrRect.h @@ -0,0 +1,37 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrRect_DEFINED +#define GrRect_DEFINED + +#include "GrPoint.h" +#include "SkRect.h" + +typedef SkIRect GrIRect; +typedef SkRect GrRect; + +struct GrIRect16 { + int16_t fLeft, fTop, fRight, fBottom; + + int width() const { return fRight - fLeft; } + int height() const { return fBottom - fTop; } + int area() const { return this->width() * this->height(); } + bool isEmpty() const { return fLeft >= fRight || fTop >= fBottom; } + + void set(const GrIRect& r) { + fLeft = SkToS16(r.fLeft); + fTop = SkToS16(r.fTop); + fRight = SkToS16(r.fRight); + fBottom = SkToS16(r.fBottom); + } +}; + +#endif + diff --git a/include/gpu/GrRefCnt.h b/include/gpu/GrRefCnt.h new file mode 100644 index 0000000..50c32c6 --- /dev/null +++ b/include/gpu/GrRefCnt.h @@ -0,0 +1,34 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrRefCnt_DEFINED +#define GrRefCnt_DEFINED + +#include "GrTypes.h" +#include "SkRefCnt.h" + +typedef SkRefCnt GrRefCnt; +typedef SkAutoRef GrAutoRef; +typedef SkAutoUnref GrAutoUnref; + +#define GrSafeRef SkSafeRef +#define GrSafeUnref SkSafeUnref +#define GrSafeAssign(a, b) SkRefCnt_SafeAssign(a, b) + +template<typename T> +static inline void GrSafeSetNull(T*& obj) { + if (NULL != obj) { + obj->unref(); + obj = NULL; + } +} + +#endif + diff --git a/include/gpu/GrRenderTarget.h b/include/gpu/GrRenderTarget.h new file mode 100644 index 0000000..13b2160 --- /dev/null +++ b/include/gpu/GrRenderTarget.h @@ -0,0 +1,206 @@ +/* + Copyright 2011 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + + +#ifndef GrRenderTarget_DEFINED +#define GrRenderTarget_DEFINED + +#include "GrRect.h" +#include "GrResource.h" + +class GrStencilBuffer; +class GrTexture; + +/** + * GrRenderTarget represents a 2D buffer of pixels that can be rendered to. + * A context's render target is set by setRenderTarget(). Render targets are + * created by a createTexture with the kRenderTarget_TextureFlag flag. + * Additionally, GrContext provides methods for creating GrRenderTargets + * that wrap externally created render targets. + */ +class GrRenderTarget : public GrResource { +public: + + /** + * @return the width of the rendertarget + */ + int width() const { return fWidth; } + /** + * @return the height of the rendertarget + */ + int height() const { return fHeight; } + + /** + * @return the pixel config. Can be kUnknown_GrPixelConfig + * if client asked us to render to a target that has a pixel + * config that isn't equivalent with one of our configs. + */ + GrPixelConfig config() const { return fConfig; } + + /** + * @return the texture associated with the rendertarget, may be NULL. + */ + GrTexture* asTexture() {return fTexture;} + + /** + * If this RT is multisampled, this is the multisample buffer + * @return the 3D API's handle to this object (e.g. FBO ID in OpenGL) + */ + virtual intptr_t getRenderTargetHandle() const = 0; + + /** + * If this RT is multisampled, this is the buffer it is resolved to. + * Otherwise, same as getRenderTargetHandle(). + * (In GL a separate FBO ID is used for the msaa and resolved buffers) + * @return the 3D API's handle to this object (e.g. FBO ID in OpenGL) + */ + virtual intptr_t getRenderTargetResolvedHandle() const = 0; + + /** + * @return true if the render target is multisampled, false otherwise + */ + bool isMultisampled() const { return 0 != fSampleCnt; } + + /** + * @return the number of samples-per-pixel or zero if non-MSAA. + */ + int numSamples() const { return fSampleCnt; } + + /** + * Call to indicate the multisample contents were modified such that the + * render target needs to be resolved before it can be used as texture. Gr + * tracks this for its own drawing and thus this only needs to be called + * when the render target has been modified outside of Gr. Only meaningful + * for Gr-created RT/Textures and Platform RT/Textures created with the + * kGrCanResolve flag. + * @param rect a rect bounding the area needing resolve. NULL indicates + * the whole RT needs resolving. + */ + void flagAsNeedingResolve(const GrIRect* rect = NULL); + + /** + * Call to override the region that needs to be resolved. + */ + void overrideResolveRect(const GrIRect rect); + + /** + * Call to indicate that GrRenderTarget was externally resolved. This may + * allow Gr to skip a redundant resolve step. + */ + void flagAsResolved() { fResolveRect.setLargestInverted(); } + + /** + * @return true if the GrRenderTarget requires MSAA resolving + */ + bool needsResolve() const { return !fResolveRect.isEmpty(); } + + /** + * Returns a rect bounding the region needing resolving. + */ + const GrIRect& getResolveRect() const { return fResolveRect; } + + // GrResource overrides + virtual size_t sizeInBytes() const; + + /** + * Reads a rectangle of pixels from the render target. + * @param left left edge of the rectangle to read (inclusive) + * @param top top edge of the rectangle to read (inclusive) + * @param width width of rectangle to read in pixels. + * @param height height of rectangle to read in pixels. + * @param config the pixel config of the destination buffer + * @param buffer memory to read the rectangle into. + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + * + * @return true if the read succeeded, false if not. The read can fail + * because of an unsupported pixel config. + */ + bool readPixels(int left, int top, int width, int height, + GrPixelConfig config, void* buffer, size_t rowBytes); + + /** + * Copy the src pixels [buffer, rowbytes, pixelconfig] into the render + * target at the specified rectangle. + * @param left left edge of the rectangle to write (inclusive) + * @param top top edge of the rectangle to write (inclusive) + * @param width width of rectangle to write in pixels. + * @param height height of rectangle to write in pixels. + * @param config the pixel config of the source buffer + * @param buffer memory to read the rectangle from. + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + */ + void writePixels(int left, int top, int width, int height, + GrPixelConfig config, const void* buffer, size_t rowBytes); + + // a MSAA RT may require explicit resolving , it may auto-resolve (e.g. FBO + // 0 in GL), or be unresolvable because the client didn't give us the + // resolve destination. + enum ResolveType { + kCanResolve_ResolveType, + kAutoResolves_ResolveType, + kCantResolve_ResolveType, + }; + virtual ResolveType getResolveType() const = 0; + + /** + * GrStencilBuffer is not part of the public API. + */ + GrStencilBuffer* getStencilBuffer() const { return fStencilBuffer; } + void setStencilBuffer(GrStencilBuffer* stencilBuffer); + +protected: + GrRenderTarget(GrGpu* gpu, + GrTexture* texture, + int width, + int height, + GrPixelConfig config, + int sampleCnt) + : INHERITED(gpu) + , fStencilBuffer(NULL) + , fTexture(texture) + , fWidth(width) + , fHeight(height) + , fConfig(config) + , fSampleCnt(sampleCnt) { + fResolveRect.setLargestInverted(); + } + + friend class GrTexture; + // When a texture unrefs an owned rendertarget this func + // removes the back pointer. This could be done called from + // texture's destructor but would have to be done in derived + // class. By the time of texture base destructor it has already + // lost its pointer to the rt. + void onTextureReleaseRenderTarget() { + GrAssert(NULL != fTexture); + fTexture = NULL; + } + +private: + GrStencilBuffer* fStencilBuffer; + GrTexture* fTexture; // not ref'ed + int fWidth; + int fHeight; + GrPixelConfig fConfig; + int fSampleCnt; + GrIRect fResolveRect; + + typedef GrResource INHERITED; +}; + +#endif diff --git a/include/gpu/GrResource.h b/include/gpu/GrResource.h new file mode 100644 index 0000000..e003353 --- /dev/null +++ b/include/gpu/GrResource.h @@ -0,0 +1,88 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef GrResource_DEFINED +#define GrResource_DEFINED + +#include "GrRefCnt.h" + +class GrGpu; +class GrContext; + +class GrResource : public GrRefCnt { +public: + explicit GrResource(GrGpu* gpu); + + virtual ~GrResource() { + // subclass should have released this. + GrAssert(!isValid()); + } + + /** + * Frees the resource in the underlying 3D API. It must be safe to call this + * when the resource has been previously abandoned. + */ + void release(); + + /** + * Removes references to objects in the underlying 3D API without freeing + * them. Used when the API context has been torn down before the GrContext. + */ + void abandon(); + + /** + * Tests whether a resource has been abandoned or released. All resources + * will be in this state after their creating GrContext is destroyed or has + * contextLost called. It's up to the client to test isValid() before + * attempting to use a resource if it holds refs on resources across + * ~GrContext, freeResources with the force flag, or contextLost. + * + * @return true if the resource has been released or abandoned, + * false otherwise. + */ + bool isValid() const { return NULL != fGpu; } + + /** + * Retrieves the size of the object in GPU memory. This is approximate since + * we aren't aware of additional padding or copies made by the driver. + * + * @return the size of the buffer in bytes + */ + virtual size_t sizeInBytes() const = 0; + + /** + * Retrieves the context that owns the resource. Note that it is possible + * for this to return NULL. When resources have been release()ed or + * abandon()ed they no longer have an unknowning context. Destroying a + * GrContext automatically releases all its resources. + */ + const GrContext* getContext() const; + GrContext* getContext(); + +protected: + + virtual void onRelease() = 0; + virtual void onAbandon() = 0; + + GrGpu* getGpu() const { return fGpu; } + +private: + GrResource(); // unimpl + + GrGpu* fGpu; // not reffed. This can outlive the GrGpu. + + friend class GrGpu; // GrGpu manages list of resources. + + GrResource* fNext; // dl-list of resources per-GrGpu + GrResource* fPrevious; + + typedef GrRefCnt INHERITED; +}; + +#endif diff --git a/include/gpu/GrSamplerState.h b/include/gpu/GrSamplerState.h new file mode 100644 index 0000000..81dfdb3 --- /dev/null +++ b/include/gpu/GrSamplerState.h @@ -0,0 +1,235 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrSamplerState_DEFINED +#define GrSamplerState_DEFINED + +#include "GrTypes.h" +#include "GrMatrix.h" + +#define MAX_KERNEL_WIDTH 25 + +class GrSamplerState { +public: + enum Filter { + /** + * Read the closest src texel to the sample position + */ + kNearest_Filter, + /** + * Blend between closest 4 src texels to sample position (tent filter) + */ + kBilinear_Filter, + /** + * Average of 4 bilinear filterings spaced +/- 1 texel from sample + * position in x and y. Intended for averaging 16 texels in a downsample + * pass. (rasterizing such that texture samples fall exactly halfway + * between texels in x and y spaced 4 texels apart.) Only supported + * on shader backends. + */ + k4x4Downsample_Filter, + /** + * Apply a separable convolution kernel. + */ + kConvolution_Filter, + + kDefault_Filter = kNearest_Filter + }; + + /** + * The intepretation of the texture matrix depends on the sample mode. The + * texture matrix is applied both when the texture coordinates are explicit + * and when vertex positions are used as texture coordinates. In the latter + * case the texture matrix is applied to the pre-view-matrix position + * values. + * + * kNormal_SampleMode + * The post-matrix texture coordinates are in normalize space with (0,0) at + * the top-left and (1,1) at the bottom right. + * kRadial_SampleMode + * The matrix specifies the radial gradient parameters. + * (0,0) in the post-matrix space is center of the radial gradient. + * kRadial2_SampleMode + * Matrix transforms to space where first circle is centered at the + * origin. The second circle will be centered (x, 0) where x may be + * 0 and is provided by setRadial2Params. The post-matrix space is + * normalized such that 1 is the second radius - first radius. + * kSweepSampleMode + * The angle from the origin of texture coordinates in post-matrix space + * determines the gradient value. + */ + enum SampleMode { + kNormal_SampleMode, //!< sample color directly + kRadial_SampleMode, //!< treat as radial gradient + kRadial2_SampleMode, //!< treat as 2-point radial gradient + kSweep_SampleMode, //!< treat as sweep gradient + + kDefault_SampleMode = kNormal_SampleMode + }; + + /** + * Describes how a texture is sampled when coordinates are outside the + * texture border + */ + enum WrapMode { + kClamp_WrapMode, + kRepeat_WrapMode, + kMirror_WrapMode, + + kDefault_WrapMode = kClamp_WrapMode + }; + + /** + * Default sampler state is set to clamp, use normal sampling mode, be + * unfiltered, and use identity matrix. + */ + GrSamplerState() + : fRadial2CenterX1() + , fRadial2Radius0() + , fRadial2PosRoot() { + this->reset(); + } + + WrapMode getWrapX() const { return fWrapX; } + WrapMode getWrapY() const { return fWrapY; } + SampleMode getSampleMode() const { return fSampleMode; } + const GrMatrix& getMatrix() const { return fMatrix; } + const GrRect& getTextureDomain() const { return fTextureDomain; } + bool hasTextureDomain() const {return SkIntToScalar(0) != fTextureDomain.right();} + Filter getFilter() const { return fFilter; } + int getKernelWidth() const { return fKernelWidth; } + const float* getKernel() const { return fKernel; } + const float* getImageIncrement() const { return fImageIncrement; } + bool swapsRAndB() const { return fSwapRAndB; } + + bool isGradient() const { + return kRadial_SampleMode == fSampleMode || + kRadial2_SampleMode == fSampleMode || + kSweep_SampleMode == fSampleMode; + } + + void setWrapX(WrapMode mode) { fWrapX = mode; } + void setWrapY(WrapMode mode) { fWrapY = mode; } + void setSampleMode(SampleMode mode) { fSampleMode = mode; } + + /** + * Access the sampler's matrix. See SampleMode for explanation of + * relationship between the matrix and sample mode. + */ + GrMatrix* matrix() { return &fMatrix; } + + /** + * Sets the sampler's texture coordinate domain to a + * custom rectangle, rather than the default (0,1). + * This option is currently only supported with kClamp_WrapMode + */ + void setTextureDomain(const GrRect& textureDomain) { fTextureDomain = textureDomain; } + + /** + * Swaps the R and B components when reading from the texture. Has no effect + * if the texture is alpha only. + */ + void setRAndBSwap(bool swap) { fSwapRAndB = swap; } + + /** + * Multiplies the current sampler matrix a matrix + * + * After this call M' = M*m where M is the old matrix, m is the parameter + * to this function, and M' is the new matrix. (We consider points to + * be column vectors so tex cood vector t is transformed by matrix X as + * t' = X*t.) + * + * @param matrix the matrix used to modify the matrix. + */ + void preConcatMatrix(const GrMatrix& matrix) { fMatrix.preConcat(matrix); } + + /** + * Sets filtering type. + * @param filter type of filtering to apply + */ + void setFilter(Filter filter) { fFilter = filter; } + + void reset(WrapMode wrapXAndY, + Filter filter, + const GrMatrix& matrix) { + fWrapX = wrapXAndY; + fWrapY = wrapXAndY; + fSampleMode = kDefault_SampleMode; + fFilter = filter; + fMatrix = matrix; + fTextureDomain.setEmpty(); + fSwapRAndB = false; + } + void reset(WrapMode wrapXAndY, + Filter filter) { + this->reset(wrapXAndY, filter, GrMatrix::I()); + } + void reset(const GrMatrix& matrix) { + this->reset(kDefault_WrapMode, kDefault_Filter, matrix); + } + void reset() { + this->reset(kDefault_WrapMode, kDefault_Filter, GrMatrix::I()); + } + + GrScalar getRadial2CenterX1() const { return fRadial2CenterX1; } + GrScalar getRadial2Radius0() const { return fRadial2Radius0; } + bool isRadial2PosRoot() const { return SkToBool(fRadial2PosRoot); } + // do the radial gradient params lead to a linear (rather than quadratic) + // equation. + bool radial2IsDegenerate() const { return GR_Scalar1 == fRadial2CenterX1; } + + /** + * Sets the parameters for kRadial2_SampleMode. The texture + * matrix must be set so that the first point is at (0,0) and the second + * point lies on the x-axis. The second radius minus the first is 1 unit. + * The additional parameters to define the gradient are specified by this + * function. + */ + void setRadial2Params(GrScalar centerX1, GrScalar radius0, bool posRoot) { + fRadial2CenterX1 = centerX1; + fRadial2Radius0 = radius0; + fRadial2PosRoot = posRoot; + } + + void setConvolutionParams(int kernelWidth, const float* kernel, float imageIncrement[2]) { + GrAssert(kernelWidth >= 0 && kernelWidth <= MAX_KERNEL_WIDTH); + fKernelWidth = kernelWidth; + if (NULL != kernel) { + memcpy(fKernel, kernel, kernelWidth * sizeof(float)); + } + if (NULL != imageIncrement) { + memcpy(fImageIncrement, imageIncrement, sizeof(fImageIncrement)); + } else { + memset(fImageIncrement, 0, sizeof(fImageIncrement)); + } + } + +private: + WrapMode fWrapX : 8; + WrapMode fWrapY : 8; + SampleMode fSampleMode : 8; + Filter fFilter : 8; + GrMatrix fMatrix; + bool fSwapRAndB; + GrRect fTextureDomain; + + // these are undefined unless fSampleMode == kRadial2_SampleMode + GrScalar fRadial2CenterX1; + GrScalar fRadial2Radius0; + SkBool8 fRadial2PosRoot; + + // These are undefined unless fFilter == kConvolution_Filter + uint8_t fKernelWidth; + float fImageIncrement[2]; + float fKernel[MAX_KERNEL_WIDTH]; +}; + +#endif + diff --git a/include/gpu/GrScalar.h b/include/gpu/GrScalar.h new file mode 100644 index 0000000..4ffc4ca --- /dev/null +++ b/include/gpu/GrScalar.h @@ -0,0 +1,49 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrScalar_DEFINED +#define GrScalar_DEFINED + +#include "GrTypes.h" +#include "SkScalar.h" + +#define GR_Int32Min SK_NaN32 +#define GR_Int32Max SK_MaxS32 + +#define GR_Fixed1 SK_Fixed1 +#define GR_FixedHalf SK_FixedHalf +#define GrIntToFixed(a) SkIntToFixed(a) +#define GrFixedToFloat(a) SkFixedToFloat(a) +#define GrFixedFloorToInt(a) SkFixedFloor(a) + +#define GrScalar SkScalar +#define GR_Scalar1 SK_Scalar1 +#define GR_ScalarHalf SK_ScalarHalf +#define GR_ScalarMin SK_ScalarMin +#define GR_ScalarMax SK_ScalarMax + +#define GrIntToScalar(a) SkIntToScalar(a) +#define GrScalarHalf(a) SkScalarHalf(a) +#define GrScalarAve(a,b) SkScalarAve(a,b) +#define GrMul(a,b) SkScalarMul(a,b) // deprecated, prefer GrScalarMul +#define GrScalarMul(a,b) SkScalarMul(a,b) +#define GrScalarDiv(a,b) SkScalarDiv(a, b) +#define GrScalarToFloat(a) SkScalarToFloat(a) +#define GrFloatToScalar(a) SkScalarToFloat(a) +#define GrIntToScalar(a) SkIntToScalar(a) +#define GrScalarAbs(a) SkScalarAbs(a) +#define GrScalarIsInt(a) SkScalarIsInt(a) +#define GrScalarMax(a,b) SkScalarMax(a,b) +#define GrScalarFloorToInt(a) SkScalarFloor(a) +#define GrScalarCeilToInt(a) SkScalarCeil(a) +#define GrFixedToScalar(a) SkFixedToScalar(a) + +#endif + diff --git a/include/gpu/GrTemplates.h b/include/gpu/GrTemplates.h new file mode 100644 index 0000000..63e43ee --- /dev/null +++ b/include/gpu/GrTemplates.h @@ -0,0 +1,69 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef GrTemplates_DEFINED +#define GrTemplates_DEFINED + +#include "GrNoncopyable.h" + +/** + * Use to cast a ptr to a different type, and maintain strict-aliasing + */ +template <typename Dst, typename Src> Dst GrTCast(Src src) { + union { + Src src; + Dst dst; + } data; + data.src = src; + return data.dst; +} + +/** + * saves value of T* in and restores in destructor + * e.g.: + * { + * GrAutoTPtrValueRestore<int*> autoCountRestore; + * if (useExtra) { + * autoCountRestore.save(&fCount); + * fCount += fExtraCount; + * } + * ... + * } // fCount is restored + */ +template <typename T> class GrAutoTPtrValueRestore : public GrNoncopyable { +public: + GrAutoTPtrValueRestore() : fPtr(NULL), fVal() {} + + GrAutoTPtrValueRestore(T* ptr) { + fPtr = ptr; + if (NULL != ptr) { + fVal = *ptr; + } + } + + ~GrAutoTPtrValueRestore() { + if (NULL != fPtr) { + *fPtr = fVal; + } + } + + // restores previously saved value (if any) and saves value for passed T* + void save(T* ptr) { + if (NULL != fPtr) { + *fPtr = fVal; + } + fPtr = ptr; + fVal = *ptr; + } +private: + T* fPtr; + T fVal; +}; + +#endif diff --git a/include/gpu/GrTextContext.h b/include/gpu/GrTextContext.h new file mode 100644 index 0000000..5983e35 --- /dev/null +++ b/include/gpu/GrTextContext.h @@ -0,0 +1,68 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrTextContext_DEFINED +#define GrTextContext_DEFINED + +#include "GrGlyph.h" +#include "GrPaint.h" +#include "GrMatrix.h" + +struct GrGpuTextVertex; +class GrContext; +class GrTextStrike; +class GrFontScaler; +class GrDrawTarget; + +class GrTextContext { +public: + GrTextContext(GrContext*, + const GrPaint& paint, + const GrMatrix* extMatrix = NULL); + ~GrTextContext(); + + void drawPackedGlyph(GrGlyph::PackedID, GrFixed left, GrFixed top, + GrFontScaler*); + + void flush(); // optional; automatically called by destructor + +private: + GrPaint fPaint; + GrVertexLayout fVertexLayout; + GrContext* fContext; + GrDrawTarget* fDrawTarget; + + GrMatrix fExtMatrix; + GrFontScaler* fScaler; + GrTextStrike* fStrike; + + inline void flushGlyphs(); + void setupDrawTarget(); + + enum { + kMinRequestedGlyphs = 1, + kDefaultRequestedGlyphs = 64, + kMinRequestedVerts = kMinRequestedGlyphs * 4, + kDefaultRequestedVerts = kDefaultRequestedGlyphs * 4, + }; + + GrGpuTextVertex* fVertices; + + int32_t fMaxVertices; + GrTexture* fCurrTexture; + int fCurrVertex; + + GrIRect fClipRect; + GrMatrix fOrigViewMatrix; // restore previous viewmatrix +}; + +#endif + + diff --git a/include/gpu/GrTexture.h b/include/gpu/GrTexture.h new file mode 100644 index 0000000..8274140 --- /dev/null +++ b/include/gpu/GrTexture.h @@ -0,0 +1,160 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrTexture_DEFINED +#define GrTexture_DEFINED + +#include "GrResource.h" + +class GrRenderTarget; + +class GrTexture : public GrResource { + +public: + /** + * Retrieves the width of the texture. + * + * @return the width in texels + */ + int width() const { return fWidth; } + + /** + * Retrieves the height of the texture. + * + * @return the height in texels + */ + int height() const { return fHeight; } + + /** + * Convert from texels to normalized texture coords for POT textures + * only. + */ + GrFixed normalizeFixedX(GrFixed x) const { GrAssert(GrIsPow2(fWidth)); + return x >> fShiftFixedX; } + GrFixed normalizeFixedY(GrFixed y) const { GrAssert(GrIsPow2(fHeight)); + return y >> fShiftFixedY; } + + /** + * Retrieves the pixel config specified when the texture was created. + */ + GrPixelConfig config() const { return fConfig; } + + /** + * Approximate number of bytes used by the texture + */ + virtual size_t sizeInBytes() const { + return (size_t) fWidth * fHeight * GrBytesPerPixel(fConfig); + } + + /** + * Read a rectangle of pixels from the texture. + * @param left left edge of the rectangle to read (inclusive) + * @param top top edge of the rectangle to read (inclusive) + * @param width width of rectangle to read in pixels. + * @param height height of rectangle to read in pixels. + * @param config the pixel config of the destination buffer + * @param buffer memory to read the rectangle into. + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + * + * @return true if the read succeeded, false if not. The read can fail + * because of a unsupported pixel config. + */ + bool readPixels(int left, int top, int width, int height, + GrPixelConfig config, void* buffer, + size_t rowBytes); + + /** + * Writes a rectangle of pixels to the texture. + * @param left left edge of the rectangle to write (inclusive) + * @param top top edge of the rectangle to write (inclusive) + * @param width width of rectangle to write in pixels. + * @param height height of rectangle to write in pixels. + * @param config the pixel config of the source buffer + * @param buffer memory to read pixels from + * @param rowBytes number of bytes bewtween consecutive rows. Zero + * means rows are tightly packed. + */ + void writePixels(int left, int top, int width, int height, + GrPixelConfig config, const void* buffer, + size_t rowBytes); + + /** + * Retrieves the render target underlying this texture that can be passed to + * GrGpu::setRenderTarget(). + * + * @return handle to render target or NULL if the texture is not a + * render target + */ + GrRenderTarget* asRenderTarget() { return fRenderTarget; } + + /** + * Removes the reference on the associated GrRenderTarget held by this + * texture. Afterwards asRenderTarget() will return NULL. The + * GrRenderTarget survives the release if another ref is held on it. + */ + void releaseRenderTarget(); + + /** + * Return the native ID or handle to the texture, depending on the + * platform. e.g. on opengl, return the texture ID. + */ + virtual intptr_t getTextureHandle() const = 0; + +#if GR_DEBUG + void validate() const { + this->INHERITED::validate(); + } +#else + void validate() const {} +#endif + +protected: + GrRenderTarget* fRenderTarget; // texture refs its rt representation + // base class cons sets to NULL + // subclass cons can create and set + + GrTexture(GrGpu* gpu, + int width, + int height, + GrPixelConfig config) + : INHERITED(gpu) + , fRenderTarget(NULL) + , fWidth(width) + , fHeight(height) + , fConfig(config) { + // only make sense if alloc size is pow2 + fShiftFixedX = 31 - Gr_clz(fWidth); + fShiftFixedY = 31 - Gr_clz(fHeight); + } + + // GrResource overrides + virtual void onRelease() { + this->releaseRenderTarget(); + } + + virtual void onAbandon(); + +private: + int fWidth; + int fHeight; + + // these two shift a fixed-point value into normalized coordinates + // for this texture if the texture is power of two sized. + int fShiftFixedX; + int fShiftFixedY; + + GrPixelConfig fConfig; + + typedef GrResource INHERITED; +}; + +#endif + diff --git a/include/gpu/GrTypes.h b/include/gpu/GrTypes.h new file mode 100644 index 0000000..0bcab7d --- /dev/null +++ b/include/gpu/GrTypes.h @@ -0,0 +1,838 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef GrTypes_DEFINED +#define GrTypes_DEFINED + +#include "SkTypes.h" +#include "GrConfig.h" + +//////////////////////////////////////////////////////////////////////////////// + +/** + * Defines overloaded bitwise operators to make it easier to use an enum as a + * bitfield. + */ +#define GR_MAKE_BITFIELD_OPS(X) \ + inline X operator | (X a, X b) { \ + return (X) (+a | +b); \ + } \ + \ + inline X operator & (X a, X b) { \ + return (X) (+a & +b); \ + } \ + template <typename T> \ + inline X operator & (T a, X b) { \ + return (X) (+a & +b); \ + } \ + template <typename T> \ + inline X operator & (X a, T b) { \ + return (X) (+a & +b); \ + } \ + +#define GR_DECL_BITFIELD_OPS_FRIENDS(X) \ + friend X operator | (X a, X b); \ + \ + friend X operator & (X a, X b); \ + \ + template <typename T> \ + friend X operator & (T a, X b); \ + \ + template <typename T> \ + friend X operator & (X a, T b); \ +//////////////////////////////////////////////////////////////////////////////// + + +/** + * Macro to round n up to the next multiple of 4, or return it unchanged if + * n is already a multiple of 4 + */ +#define GrALIGN4(n) SkAlign4(n) +#define GrIsALIGN4(n) SkIsAlign4(n) + +template <typename T> const T& GrMin(const T& a, const T& b) { + return (a < b) ? a : b; +} + +template <typename T> const T& GrMax(const T& a, const T& b) { + return (b < a) ? a : b; +} + +// compile time versions of min/max +#define GR_CT_MAX(a, b) (((b) < (a)) ? (a) : (b)) +#define GR_CT_MIN(a, b) (((b) < (a)) ? (b) : (a)) + +/** + * divide, rounding up + */ +static inline int32_t GrIDivRoundUp(int x, int y) { + GrAssert(y > 0); + return (x + (y-1)) / y; +} +static inline uint32_t GrUIDivRoundUp(uint32_t x, uint32_t y) { + return (x + (y-1)) / y; +} +static inline size_t GrSizeDivRoundUp(size_t x, uint32_t y) { + return (x + (y-1)) / y; +} + +/** + * align up + */ +static inline uint32_t GrUIAlignUp(uint32_t x, uint32_t alignment) { + return GrUIDivRoundUp(x, alignment) * alignment; +} +static inline uint32_t GrSizeAlignUp(size_t x, uint32_t alignment) { + return GrSizeDivRoundUp(x, alignment) * alignment; +} + +/** + * amount of pad needed to align up + */ +static inline uint32_t GrUIAlignUpPad(uint32_t x, uint32_t alignment) { + return (alignment - x % alignment) % alignment; +} +static inline size_t GrSizeAlignUpPad(size_t x, uint32_t alignment) { + return (alignment - x % alignment) % alignment; +} + +/** + * align down + */ +static inline uint32_t GrUIAlignDown(uint32_t x, uint32_t alignment) { + return (x / alignment) * alignment; +} +static inline uint32_t GrSizeAlignDown(size_t x, uint32_t alignment) { + return (x / alignment) * alignment; +} + +/** + * Count elements in an array + */ +#define GR_ARRAY_COUNT(array) SK_ARRAY_COUNT(array) + +//!< allocate a block of memory, will never return NULL +extern void* GrMalloc(size_t bytes); + +//!< free block allocated by GrMalloc. ptr may be NULL +extern void GrFree(void* ptr); + +static inline void Gr_bzero(void* dst, size_t size) { + memset(dst, 0, size); +} + +/////////////////////////////////////////////////////////////////////////////// + +/** + * Return the number of leading zeros in n + */ +extern int Gr_clz(uint32_t n); + +/** + * Return true if n is a power of 2 + */ +static inline bool GrIsPow2(unsigned n) { + return n && 0 == (n & (n - 1)); +} + +/** + * Return the next power of 2 >= n. + */ +static inline uint32_t GrNextPow2(uint32_t n) { + return n ? (1 << (32 - Gr_clz(n - 1))) : 1; +} + +static inline int GrNextPow2(int n) { + GrAssert(n >= 0); // this impl only works for non-neg. + return n ? (1 << (32 - Gr_clz(n - 1))) : 1; +} + +/////////////////////////////////////////////////////////////////////////////// + +/** + * 16.16 fixed point type + */ +typedef int32_t GrFixed; + +#if GR_DEBUG + +static inline int16_t GrToS16(intptr_t x) { + GrAssert((int16_t)x == x); + return (int16_t)x; +} + +#else + +#define GrToS16(x) x + +#endif + + +/////////////////////////////////////////////////////////////////////////////// + +/** + * Possible 3D APIs that may be used by Ganesh. + */ +enum GrEngine { + kOpenGL_Shaders_GrEngine, + kOpenGL_Fixed_GrEngine, +}; + +/** + * Engine-specific 3D context handle + * GrGLInterface* for OpenGL. If NULL will use the default GL interface. + */ +typedef intptr_t GrPlatform3DContext; + +/////////////////////////////////////////////////////////////////////////////// + +/** + * Type used to describe format of vertices in arrays + * Values are defined in GrDrawTarget + */ +typedef int GrVertexLayout; + +/** +* Geometric primitives used for drawing. +*/ +enum GrPrimitiveType { + kTriangles_PrimitiveType, + kTriangleStrip_PrimitiveType, + kTriangleFan_PrimitiveType, + kPoints_PrimitiveType, + kLines_PrimitiveType, // 1 pix wide only + kLineStrip_PrimitiveType // 1 pix wide only +}; + +static inline bool GrIsPrimTypeLines(GrPrimitiveType type) { + return kLines_PrimitiveType == type || kLineStrip_PrimitiveType == type; +} + +static inline bool GrIsPrimTypeTris(GrPrimitiveType type) { + return kTriangles_PrimitiveType == type || + kTriangleStrip_PrimitiveType == type || + kTriangleFan_PrimitiveType == type; +} + +/** + * Coeffecients for alpha-blending. + */ +enum GrBlendCoeff { + kZero_BlendCoeff, //<! 0 + kOne_BlendCoeff, //<! 1 + kSC_BlendCoeff, //<! src color + kISC_BlendCoeff, //<! one minus src color + kDC_BlendCoeff, //<! dst color + kIDC_BlendCoeff, //<! one minus dst color + kSA_BlendCoeff, //<! src alpha + kISA_BlendCoeff, //<! one minus src alpha + kDA_BlendCoeff, //<! dst alpha + kIDA_BlendCoeff, //<! one minus dst alpha + kConstC_BlendCoeff, //<! constant color + kIConstC_BlendCoeff, //<! one minus constant color + kConstA_BlendCoeff, //<! constant color alpha + kIConstA_BlendCoeff, //<! one minus constant color alpha + + kPublicBlendCoeffCount +}; + +/** + * Formats for masks, used by the font cache. + * Important that these are 0-based. + */ +enum GrMaskFormat { + kA8_GrMaskFormat, //!< 1-byte per pixel + kA565_GrMaskFormat, //!< 2-bytes per pixel + kA888_GrMaskFormat, //!< 4-bytes per pixel + + kCount_GrMaskFormats //!< used to allocate arrays sized for mask formats +}; + +/** + * Return the number of bytes-per-pixel for the specified mask format. + */ +static inline int GrMaskFormatBytesPerPixel(GrMaskFormat format) { + GrAssert((unsigned)format <= 2); + // kA8 (0) -> 1 + // kA565 (1) -> 2 + // kA888 (2) -> 4 + return 1 << (int)format; +} + +/** + * Pixel configurations. + * + * Unpremultiplied configs are intended for converting pixel data in and out + * from skia. Surfaces with these configs have limited support. As an input + * (GrPaint texture) the corresponding GrSamplerState must have its filter set + * to kNearest_Filter. Otherwise, the draw will fail. When the render target + * has an unpremultiplied config draws must use blend coeffs 1,0 (AKA src-mode). + * Other coeffs will cause the draw to fail. + */ +enum GrPixelConfig { + kUnknown_GrPixelConfig, + kAlpha_8_GrPixelConfig, + kIndex_8_GrPixelConfig, + kRGB_565_GrPixelConfig, + /** + * Premultiplied + */ + kRGBA_4444_GrPixelConfig, + /** + * Premultiplied. Byte order is r,g,b,a + */ + kRGBA_8888_PM_GrPixelConfig, + /** + * Unpremultiplied. Byte order is r,g,b,a + */ + kRGBA_8888_UPM_GrPixelConfig, + /** + * Premultiplied. Byte order is b,g,r,a + */ + kBGRA_8888_PM_GrPixelConfig, + /** + * Unpremultiplied. Byte order is b,g,r,a + */ + kBGRA_8888_UPM_GrPixelConfig, +}; + +// Aliases for pixel configs that match skia's byte order +#ifndef SK_CPU_LENDIAN + #error "Skia gpu currently assumes little endian" +#endif +#if 24 == SK_A32_SHIFT && 16 == SK_R32_SHIFT && \ + 8 == SK_G32_SHIFT && 0 == SK_B32_SHIFT + static const GrPixelConfig kSkia8888_PM_GrPixelConfig = kBGRA_8888_PM_GrPixelConfig; + static const GrPixelConfig kSkia8888_UPM_GrPixelConfig = kBGRA_8888_UPM_GrPixelConfig; +#elif 24 == SK_A32_SHIFT && 16 == SK_B32_SHIFT && \ + 8 == SK_G32_SHIFT && 0 == SK_R32_SHIFT + static const GrPixelConfig kSkia8888_PM_GrPixelConfig = kRGBA_8888_PM_GrPixelConfig; + static const GrPixelConfig kSkia8888_UPM_GrPixelConfig = kRGBA_8888_UPM_GrPixelConfig; +#else + #error "SK_*32_SHIFT values must correspond to GL_BGRA or GL_RGBA format." +#endif + +// WebKit is relying on this old name for the native skia PM config. This will +// be deleted ASAP because it is so similar to kRGBA_PM_8888_GrPixelConfig but +// has a different interpretation when skia is compiled BGRA. +static const GrPixelConfig kRGBA_8888_GrPixelConfig = kSkia8888_PM_GrPixelConfig; + +// Returns true if the pixel config has 8bit r,g,b,a components in that byte +// order +static inline bool GrPixelConfigIsRGBA8888(GrPixelConfig config) { + switch (config) { + case kRGBA_8888_PM_GrPixelConfig: + case kRGBA_8888_UPM_GrPixelConfig: + return true; + default: + return false; + } +} + +// Returns true if the pixel config has 8bit b,g,r,a components in that byte +// order +static inline bool GrPixelConfigIsBGRA8888(GrPixelConfig config) { + switch (config) { + case kBGRA_8888_PM_GrPixelConfig: + case kBGRA_8888_UPM_GrPixelConfig: + return true; + default: + return false; + } +} + +// Returns true if the pixel config is 32 bits per pixel +static inline bool GrPixelConfigIs32Bit(GrPixelConfig config) { + switch (config) { + case kRGBA_8888_PM_GrPixelConfig: + case kRGBA_8888_UPM_GrPixelConfig: + case kBGRA_8888_PM_GrPixelConfig: + case kBGRA_8888_UPM_GrPixelConfig: + return true; + default: + return false; + } +} + +// Takes a config and returns the equivalent config with the R and B order +// swapped if such a config exists. Otherwise, kUnknown_GrPixelConfig +static inline GrPixelConfig GrPixelConfigSwapRAndB(GrPixelConfig config) { + switch (config) { + case kBGRA_8888_PM_GrPixelConfig: + return kRGBA_8888_PM_GrPixelConfig; + case kBGRA_8888_UPM_GrPixelConfig: + return kRGBA_8888_UPM_GrPixelConfig; + case kRGBA_8888_PM_GrPixelConfig: + return kBGRA_8888_PM_GrPixelConfig; + case kRGBA_8888_UPM_GrPixelConfig: + return kBGRA_8888_UPM_GrPixelConfig; + default: + return kUnknown_GrPixelConfig; + } +} + +static inline size_t GrBytesPerPixel(GrPixelConfig config) { + switch (config) { + case kAlpha_8_GrPixelConfig: + case kIndex_8_GrPixelConfig: + return 1; + case kRGB_565_GrPixelConfig: + case kRGBA_4444_GrPixelConfig: + return 2; + case kRGBA_8888_PM_GrPixelConfig: + case kRGBA_8888_UPM_GrPixelConfig: + case kBGRA_8888_PM_GrPixelConfig: + case kBGRA_8888_UPM_GrPixelConfig: + return 4; + default: + return 0; + } +} + +static inline bool GrPixelConfigIsOpaque(GrPixelConfig config) { + switch (config) { + case kRGB_565_GrPixelConfig: + return true; + default: + return false; + } +} + +/** + * Premultiplied alpha is the usual for skia. Therefore, configs that are + * ambiguous (alpha-only or color-only) are considered premultiplied. + */ +static inline bool GrPixelConfigIsUnpremultiplied(GrPixelConfig config) { + switch (config) { + case kRGBA_8888_UPM_GrPixelConfig: + case kBGRA_8888_UPM_GrPixelConfig: + return true; + default: + return false; + } +} + +static inline bool GrPixelConfigIsAlphaOnly(GrPixelConfig config) { + switch (config) { + case kAlpha_8_GrPixelConfig: + return true; + default: + return false; + } +} + +/** + * Used to control the level of antialiasing available for a rendertarget. + * Anti-alias quality levels depend on the underlying API/GPU capabilities. + */ +enum GrAALevels { + kNone_GrAALevel, //<! No antialiasing available. + kLow_GrAALevel, //<! Low quality antialiased rendering. Actual + // interpretation is platform-dependent. + kMed_GrAALevel, //<! Medium quality antialiased rendering. Actual + // interpretation is platform-dependent. + kHigh_GrAALevel, //<! High quality antialiased rendering. Actual + // interpretation is platform-dependent. +}; + +/** + * Optional bitfield flags that can be passed to createTexture. + */ +enum GrTextureFlags { + kNone_GrTextureFlags = 0x0, + /** + * Creates a texture that can be rendered to as a GrRenderTarget. Use + * GrTexture::asRenderTarget() to access. + */ + kRenderTarget_GrTextureFlagBit = 0x1, + /** + * By default all render targets have an associated stencil buffer that + * may be required for path filling. This flag overrides stencil buffer + * creation. + * MAKE THIS PRIVATE? + */ + kNoStencil_GrTextureFlagBit = 0x2, + /** + * Hint that the CPU may modify this texture after creation. + */ + kDynamicUpdate_GrTextureFlagBit = 0x4, +}; + +GR_MAKE_BITFIELD_OPS(GrTextureFlags) + +enum { + /** + * For Index8 pixel config, the colortable must be 256 entries + */ + kGrColorTableSize = 256 * 4 //sizeof(GrColor) +}; + +/** + * Describes a texture to be created. + */ +struct GrTextureDesc { + GrTextureFlags fFlags; //!< bitfield of TextureFlags + /** + * The level of antialiasing available for a rendertarget texture. Only used + * fFlags contains kRenderTarget_GrTextureFlag. + */ + GrAALevels fAALevel; + int fWidth; //!< Width of the texture + int fHeight; //!< Height of the texture + /** + * Format of source data of the texture. Not guaraunteed to be the same as + * internal format used by 3D API. + */ + GrPixelConfig fConfig; +}; + +/** + * Set Operations used to construct clips. + */ +enum GrSetOp { + kReplace_SetOp, + kIntersect_SetOp, + kUnion_SetOp, + kXor_SetOp, + kDifference_SetOp, + kReverseDifference_SetOp, +}; + +/** + * Clips are composed from these objects. + */ +enum GrClipType { + kRect_ClipType, + kPath_ClipType +}; + +/** + * Commands used to describe a path. Each command + * is accompanied by some number of points. + */ +enum GrPathCmd { + kMove_PathCmd, //!< Starts a new subpath at + // at the returned point + // 1 point + kLine_PathCmd, //!< Adds a line segment + // 2 points + kQuadratic_PathCmd, //!< Adds a quadratic segment + // 3 points + kCubic_PathCmd, //!< Adds a cubic segment + // 4 points + kClose_PathCmd, //!< Closes the current subpath + // by connecting a line to the + // starting point. + // 0 points + kEnd_PathCmd //!< Indicates the end of the last subpath + // when iterating + // 0 points. +}; + +/** + * Gets the number of points associated with a path command. + */ +static int inline NumPathCmdPoints(GrPathCmd cmd) { + static const int gNumPoints[] = { + 1, 2, 3, 4, 0, 0 + }; + return gNumPoints[cmd]; +} + +/** + * Path filling rules + */ +enum GrPathFill { + kWinding_PathFill, + kEvenOdd_PathFill, + kInverseWinding_PathFill, + kInverseEvenOdd_PathFill, + kHairLine_PathFill, + + kPathFillCount +}; + +static inline GrPathFill GrNonInvertedFill(GrPathFill fill) { + static const GrPathFill gNonInvertedFills[] = { + kWinding_PathFill, // kWinding_PathFill + kEvenOdd_PathFill, // kEvenOdd_PathFill + kWinding_PathFill, // kInverseWinding_PathFill + kEvenOdd_PathFill, // kInverseEvenOdd_PathFill + kHairLine_PathFill,// kHairLine_PathFill + }; + GR_STATIC_ASSERT(0 == kWinding_PathFill); + GR_STATIC_ASSERT(1 == kEvenOdd_PathFill); + GR_STATIC_ASSERT(2 == kInverseWinding_PathFill); + GR_STATIC_ASSERT(3 == kInverseEvenOdd_PathFill); + GR_STATIC_ASSERT(4 == kHairLine_PathFill); + GR_STATIC_ASSERT(5 == kPathFillCount); + return gNonInvertedFills[fill]; +} + +static inline bool GrIsFillInverted(GrPathFill fill) { + static const bool gIsFillInverted[] = { + false, // kWinding_PathFill + false, // kEvenOdd_PathFill + true, // kInverseWinding_PathFill + true, // kInverseEvenOdd_PathFill + false, // kHairLine_PathFill + }; + GR_STATIC_ASSERT(0 == kWinding_PathFill); + GR_STATIC_ASSERT(1 == kEvenOdd_PathFill); + GR_STATIC_ASSERT(2 == kInverseWinding_PathFill); + GR_STATIC_ASSERT(3 == kInverseEvenOdd_PathFill); + GR_STATIC_ASSERT(4 == kHairLine_PathFill); + GR_STATIC_ASSERT(5 == kPathFillCount); + return gIsFillInverted[fill]; +} + +/** + * Hints provided about a path's convexity (or lack thereof). + */ +enum GrConvexHint { + kNone_ConvexHint, //<! No hint about convexity + // of the path + kConvex_ConvexHint, //<! Path is one convex piece + kNonOverlappingConvexPieces_ConvexHint, //<! Multiple convex pieces, + // pieces are known to be + // disjoint + kSameWindingConvexPieces_ConvexHint, //<! Multiple convex pieces, + // may or may not intersect, + // either all wind cw or all + // wind ccw. + kConcave_ConvexHint //<! Path is known to be + // concave +}; + +/////////////////////////////////////////////////////////////////////////////// + +// opaque type for 3D API object handles +typedef intptr_t GrPlatform3DObject; + +/** + * Gr can wrap an existing texture created by the client with a GrTexture + * object. The client is responsible for ensuring that the texture lives at + * least as long as the GrTexture object wrapping it. We require the client to + * explicitly provide information about the texture, such as width, height, + * and pixel config, rather than querying the 3D APIfor these values. We expect + * these to be immutable even if the 3D API doesn't require this (OpenGL). + * + * Textures that are also render targets are supported as well. Gr will manage + * any ancillary 3D API (stencil buffer, FBO id, etc) objects necessary for + * Gr to draw into the render target. To access the render target object + * call GrTexture::asRenderTarget(). + * + * If in addition to the render target flag, the caller also specifies a sample + * count Gr will create an MSAA buffer that resolves into the texture. Gr auto- + * resolves when it reads from the texture. The client can explictly resolve + * using the GrRenderTarget interface. + */ + +enum GrPlatformTextureFlags { + /** + * No flags enabled + */ + kNone_GrPlatformTextureFlag = 0x0, + /** + * Indicates that the texture is also a render target, and thus should have + * a GrRenderTarget object. + * + * D3D (future): client must have created the texture with flags that allow + * it to be used as a render target. + */ + kRenderTarget_GrPlatformTextureFlag = 0x1, +}; +GR_MAKE_BITFIELD_OPS(GrPlatformTextureFlags) + +struct GrPlatformTextureDesc { + GrPlatformTextureDesc() { memset(this, 0, sizeof(*this)); } + GrPlatformTextureFlags fFlags; + int fWidth; //<! width in pixels + int fHeight; //<! height in pixels + GrPixelConfig fConfig; //<! color format + /** + * If the render target flag is set and sample count is greater than 0 + * then Gr will create an MSAA buffer that resolves to the texture. + */ + int fSampleCnt; + /** + * Handle to the 3D API object. + * OpenGL: Texture ID. + */ + GrPlatform3DObject fTextureHandle; +}; + +/////////////////////////////////////////////////////////////////////////////// + +/** + * Gr can wrap an existing render target created by the client in the 3D API + * with a GrRenderTarget object. The client is responsible for ensuring that the + * underlying 3D API object lives at least as long as the GrRenderTarget object + * wrapping it. We require the client to explicitly provide information about + * the target, such as width, height, and pixel config rather than querying the + * 3D API for these values. We expect these properties to be immutable even if + * the 3D API doesn't require this (OpenGL). + */ + +struct GrPlatformRenderTargetDesc { + GrPlatformRenderTargetDesc() { memset(this, 0, sizeof(*this)); } + int fWidth; //<! width in pixels + int fHeight; //<! height in pixels + GrPixelConfig fConfig; //<! color format + /** + * The number of samples per pixel. Gr uses this to influence decisions + * about applying other forms of antialiasing. + */ + int fSampleCnt; + /** + * Number of bits of stencil per-pixel. + */ + int fStencilBits; + /** + * Handle to the 3D API object. + * OpenGL: FBO ID + */ + GrPlatform3DObject fRenderTargetHandle; +}; + +/////////////////////////////////////////////////////////////////////////////// +// DEPRECATED. createPlatformSurface is replaced by createPlatformTexture +// and createPlatformRenderTarget. These enums and structs will be removed. + +enum GrPlatformSurfaceType { + /** + * Specifies that the object being created is a render target. + */ + kRenderTarget_GrPlatformSurfaceType, + /** + * Specifies that the object being created is a texture. + */ + kTexture_GrPlatformSurfaceType, + /** + * Specifies that the object being created is a texture and a render + * target. + */ + kTextureRenderTarget_GrPlatformSurfaceType, +}; + +enum GrPlatformRenderTargetFlags { + kNone_GrPlatformRenderTargetFlagBit = 0x0, + + /** + * Gives permission to Gr to perform the downsample-resolve of a + * multisampled render target. If this is not set then read pixel + * operations may fail. If the object is both a texture and render target + * then this *must* be set. Otherwise, if the client wants do its own + * resolves it must create separate GrRenderTarget and GrTexture objects + * and insert appropriate flushes and resolves betweeen data hazards. + * GrRenderTarget has a flagForResolve() + */ + kGrCanResolve_GrPlatformRenderTargetFlagBit = 0x2, +}; + +GR_MAKE_BITFIELD_OPS(GrPlatformRenderTargetFlags) + +struct GrPlatformSurfaceDesc { + GrPlatformSurfaceType fSurfaceType; // type of surface to create + /** + * Flags for kRenderTarget and kTextureRenderTarget surface types + */ + GrPlatformRenderTargetFlags fRenderTargetFlags; + + int fWidth; // width in pixels + int fHeight; // height in pixels + GrPixelConfig fConfig; // color format + /** + * Number of per sample stencil buffer. Only relevant if kIsRenderTarget is + * set in fFlags. + */ + int fStencilBits; + + /** + * Number of samples per-pixel. Only relevant if kIsRenderTarget is set in + * fFlags. + */ + int fSampleCnt; + + /** + * Texture object in 3D API. Only relevant if fSurfaceType is kTexture or + * kTextureRenderTarget. + * GL: this is a texture object (glGenTextures) + */ + GrPlatform3DObject fPlatformTexture; + /** + * Render target object in 3D API. Only relevant if fSurfaceType is + * kRenderTarget or kTextureRenderTarget + * GL: this is a FBO object (glGenFramebuffers) + */ + GrPlatform3DObject fPlatformRenderTarget; + /** + * 3D API object used as destination of resolve. Only relevant if + * fSurfaceType is kRenderTarget or kTextureRenderTarget and + * kGrCanResolve is set in fRenderTargetFlags. + * fFlags. + * GL: this is a FBO object (glGenFramebuffers) + */ + GrPlatform3DObject fPlatformResolveDestination; + + void reset() { memset(this, 0, sizeof(GrPlatformSurfaceDesc)); } +}; + +/** + * Example of how to wrap render-to-texture-with-MSAA GL objects with a GrPlatformSurace + * + * GLint colorBufferID; + * glGenRenderbuffers(1, &colorID); + * glBindRenderbuffer(GL_RENDERBUFFER, colorBufferID); + * glRenderbufferStorageMultisample(GL_RENDERBUFFER, S, GL_RGBA, W, H); + * + * GLint stencilBufferID; + * glGenRenderBuffers(1, &stencilBufferID); + * glBindRenderbuffer(GL_RENDERBUFFER, stencilBufferID); + * glRenderbufferStorageMultisample(GL_RENDERBUFFER, S, GL_STENCIL_INDEX8, W, H); + * + * GLint drawFBOID; + * glGenFramebuffers(1, &drawFBOID); + * glBindFramebuffer(GL_FRAMEBUFFER, drawFBOID); + * glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorBufferID); + * glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, stencilBufferID); + * + * GLint textureID; + * glGenTextures(1, &textureID); + * glBindTexture(GL_TEXTURE_2D, textureID); + * glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, W, H, ...); + * + * GLint readFBOID; + * glGenFramebuffers(1, &readFBOID); + * glBindFramebuffer(GL_FRAMEBUFFER, readFBOID); + * glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureID, 0); + * + * GrPlatformSurfaceDesc renderTargetTextureDesc; + * renderTargetTextureDesc.fSurfaceType = kTextureRenderTarget_GrPlatformSurfaceType; + * renderTargetTextureDesc.fRenderTargetFlags = kGrCanResolve_GrPlatformRenderTargetFlagBit; + * renderTargetTextureDesc.fWidth = W; + * renderTargetTextureDesc.fHeight = H; + * renderTargetTextureDesc.fConfig = kSkia8888_PM_GrPixelConfig + * renderTargetTextureDesc.fStencilBits = 8; + * renderTargetTextureDesc.fSampleCnt = S; + * renderTargetTextureDesc.fPlatformTexture = textureID; + * renderTargetTextureDesc.fPlatformRenderTarget = drawFBOID; + * renderTargetTextureDesc.fPlatformResolveDestination = readFBOID; + * + * GrTexture* texture = static_cast<GrTexture*>(grContext->createPlatrformSurface(renderTargetTextureDesc)); + */ + + +/////////////////////////////////////////////////////////////////////////////// + +// this is included only to make it easy to use this debugging facility +#include "GrInstanceCounter.h" + +#endif diff --git a/include/gpu/GrUserConfig.h b/include/gpu/GrUserConfig.h new file mode 100644 index 0000000..657f74f --- /dev/null +++ b/include/gpu/GrUserConfig.h @@ -0,0 +1,63 @@ + +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef GrUserConfig_DEFINED +#define GrUserConfig_DEFINED + +#if defined(GR_USER_CONFIG_FILE) + #error "default user config pulled in but GR_USER_CONFIG_FILE is defined." +#endif + +#if 0 + #undef GR_RELEASE + #undef GR_DEBUG + #define GR_RELEASE 0 + #define GR_DEBUG 1 +#endif + +/* + * To diagnose texture cache performance, define this to 1 if you want to see + * a log statement everytime we upload an image to create a texture. + */ +//#define GR_DUMP_TEXTURE_UPLOAD 1 + +/* + * When drawing rects this causes Ganesh to use a vertex buffer containing + * a unit square that is positioned by a matrix. Enable on systems where + * emitting per-rect-draw verts is more expensive than constant/matrix + * updates. Defaults to 0. + */ +//#define GR_STATIC_RECT_VB 1 + +/* + * This causes more aggressive shader optimization. May hurt performance if + * switching shaders is expensive. + */ +//#define GR_AGGRESSIVE_SHADER_OPTS 1 + +/* + * This gives a threshold in bytes of when to lock a GrGeometryBuffer vs using + * updateData. (Note the depending on the underlying 3D API the update functions + * may always be implemented using a lock) + */ +//#define GR_GEOM_BUFFER_LOCK_THRESHOLD (1<<15) + +/////////////////////////////////////////////////////////////////////////////// +// Decide Ganesh types + +#define GR_SCALAR_IS_FIXED 0 +#define GR_SCALAR_IS_FLOAT 1 + +#define GR_TEXT_SCALAR_IS_USHORT 0 +#define GR_TEXT_SCALAR_IS_FIXED 0 +#define GR_TEXT_SCALAR_IS_FLOAT 1 + +#endif + + diff --git a/include/gpu/SkGLContext.h b/include/gpu/SkGLContext.h new file mode 100644 index 0000000..f92a770 --- /dev/null +++ b/include/gpu/SkGLContext.h @@ -0,0 +1,59 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef SkGLContext_DEFINED +#define SkGLContext_DEFINED + +#include "GrGLInterface.h" + +/** + * Create an offscreen opengl context with an RGBA8 / 8bit stencil FBO. + * Provides a GrGLInterface struct of function pointers for the context. + */ + +class SkGLContext : public SkRefCnt { +public: + SkGLContext(); + virtual ~SkGLContext(); + + /** + * Initializes the context and makes it current. + */ + bool init(const int width, const int height); + + int getFBOID() const { return fFBO; } + + const GrGLInterface* gl() const { return fGL; } + + virtual void makeCurrent() const = 0; + +protected: + /** + * Subclass implements this to make a GL context. The returned GrGLInterface + * should be populated with functions compatible with the context. The + * format and size of backbuffers does not matter since an FBO will be + * created. + */ + virtual const GrGLInterface* createGLContext() = 0; + + /** + * Subclass should destroy the underlying GL context. + */ + virtual void destroyGLContext() = 0; + +private: + GrGLuint fFBO; + const GrGLInterface* fGL; +}; + +/** + * Helper macro for using the GL context through the GrGLInterface. Example: + * SK_GL(glCtx, GenTextures(1, &texID)); + */ +#define SK_GL(ctx, X) (ctx).gl()->f ## X + +#endif diff --git a/include/gpu/SkGpuCanvas.h b/include/gpu/SkGpuCanvas.h index 57a4b1b..825c567 100644 --- a/include/gpu/SkGpuCanvas.h +++ b/include/gpu/SkGpuCanvas.h @@ -1,20 +1,13 @@ -/* - Copyright 2010 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkGpuCanvas_DEFINED #define SkGpuCanvas_DEFINED @@ -36,10 +29,6 @@ public: * GrRenderTarget represents the rendering destination in the underlying * 3D API. Its reference count is incremented in the constructor and * decremented in the destructor. - * SkGpuDevice::Current3DApiRenderTarget() can be passed as a special - * value that will cause the factory to create a render target object - * that reflects the state of the underlying 3D API at the time of - * construction. */ explicit SkGpuCanvas(GrContext*, GrRenderTarget*); virtual ~SkGpuCanvas(); diff --git a/include/gpu/SkGpuDevice.h b/include/gpu/SkGpuDevice.h index 601da09..6c4285e 100644 --- a/include/gpu/SkGpuDevice.h +++ b/include/gpu/SkGpuDevice.h @@ -1,26 +1,21 @@ -/* - Copyright 2010 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkGpuDevice_DEFINED #define SkGpuDevice_DEFINED #include "SkGr.h" +#include "SkBitmap.h" #include "SkDevice.h" #include "SkRegion.h" +#include "GrContext.h" struct SkDrawProcs; struct GrSkDrawProcs; @@ -33,86 +28,81 @@ class GrTextContext; class SK_API SkGpuDevice : public SkDevice { public: /** - * The SkGpuDevice will render to the GrRenderTarget, or if the paremeter is - * null it will create its own render target and manage that target's - * lifetime. + * New device that will create an offscreen renderTarget based on the + * config, width, height. + * + * usage is a special flag that should only be set by SkCanvas + * internally. */ - SkGpuDevice(GrContext*, - const SkBitmap& bitmap, - GrRenderTarget* renderTargetOrNull); + SkGpuDevice(GrContext*, SkBitmap::Config, + int width, int height, + SkDevice::Usage usage = SkDevice::kGeneral_Usage); /** - * Magic value that can be passed to constructor. Causes - * the device to infer rendertarget from underlying 3D API (e.g. GL or D3D). - * This isn't a valid pointer, don't attempt to dereference. + * New device that will render to the specified renderTarget. */ - static GrRenderTarget* Current3DApiRenderTarget(); - - virtual ~SkGpuDevice(); - - GrContext* context() const { return fContext; } + SkGpuDevice(GrContext*, GrRenderTarget*); /** - * If this device was built for rendering as a layer (i.e. offscreen), - * then this will return the platform-specific handle to that GPU resource. - * For example, in OpenGL, this will return the FBO's texture ID. - * If this device was not built for rendering as a layer, then 0 - * is returned. + * New device that will render to the texture (as a rendertarget). + * The GrTexture's asRenderTarget() must be non-NULL or device will not + * function. */ - intptr_t getLayerTextureHandle() const; + SkGpuDevice(GrContext*, GrTexture*); - // call to set the clip to the specified rect - void scissor(const SkIRect&); + virtual ~SkGpuDevice(); + + GrContext* context() const { return fContext; } /** * Override from SkGpuDevice, so we can set our FBO to be the render target * The canvas parameter must be a SkGpuCanvas */ virtual void gainFocus(SkCanvas*, const SkMatrix&, const SkRegion&, - const SkClipStack& clipStack); + const SkClipStack& clipStack) SK_OVERRIDE; - virtual SkGpuTexture* accessTexture() { return (SkGpuTexture*)fTexture; } + virtual SkGpuRenderTarget* accessRenderTarget() SK_OVERRIDE; // overrides from SkDevice - virtual void clear(SkColor color); - virtual bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap); - virtual void writePixels(const SkBitmap& bitmap, int x, int y); + virtual void clear(SkColor color) SK_OVERRIDE; + virtual void writePixels(const SkBitmap& bitmap, int x, int y, + SkCanvas::Config8888 config8888) SK_OVERRIDE; virtual void setMatrixClip(const SkMatrix& matrix, const SkRegion& clip, - const SkClipStack&); + const SkClipStack&) SK_OVERRIDE; - virtual void drawPaint(const SkDraw&, const SkPaint& paint); + virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE; virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count, - const SkPoint[], const SkPaint& paint); + const SkPoint[], const SkPaint& paint) SK_OVERRIDE; virtual void drawRect(const SkDraw&, const SkRect& r, - const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; virtual void drawPath(const SkDraw&, const SkPath& path, const SkPaint& paint, const SkMatrix* prePathMatrix, - bool pathIsMutable); + bool pathIsMutable) SK_OVERRIDE; virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap, const SkIRect* srcRectOrNull, - const SkMatrix& matrix, const SkPaint& paint); + const SkMatrix&, const SkPaint&) SK_OVERRIDE; virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap, int x, int y, const SkPaint& paint); virtual void drawText(const SkDraw&, const void* text, size_t len, - SkScalar x, SkScalar y, const SkPaint& paint); + SkScalar x, SkScalar y, const SkPaint&) SK_OVERRIDE; virtual void drawPosText(const SkDraw&, const void* text, size_t len, const SkScalar pos[], SkScalar constY, - int scalarsPerPos, const SkPaint& paint); + int scalarsPerPos, const SkPaint&) SK_OVERRIDE; virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len, const SkPath& path, const SkMatrix* matrix, - const SkPaint& paint); + const SkPaint&) SK_OVERRIDE; virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount, const SkPoint verts[], const SkPoint texs[], const SkColor colors[], SkXfermode* xmode, const uint16_t indices[], int indexCount, - const SkPaint& paint); + const SkPaint&) SK_OVERRIDE; virtual void drawDevice(const SkDraw&, SkDevice*, int x, int y, - const SkPaint&); - virtual bool filterTextFlags(const SkPaint& paint, TextFlags*); + const SkPaint&) SK_OVERRIDE; + virtual bool filterTextFlags(const SkPaint&, TextFlags*) SK_OVERRIDE; - virtual void flush() { fContext->flush(false); } + virtual void flush(); /** * Make's this device's rendertarget current in the underlying 3D API. @@ -120,33 +110,46 @@ public: */ virtual void makeRenderTargetCurrent(); + virtual bool filterImage(SkImageFilter*, const SkBitmap& src, + const SkMatrix& ctm, + SkBitmap* result, SkIPoint* offset) SK_OVERRIDE; + protected: - // override - virtual SkDeviceFactory* onNewDeviceFactory(); - - class TexCache; - TexCache* lockCachedTexture(const SkBitmap& bitmap, - const GrSamplerState& sampler, - GrTexture** texture, - bool forDeviceRenderTarget = false); - void unlockCachedTexture(TexCache*); + typedef GrContext::TextureCacheEntry TexCache; + enum TexType { + kBitmap_TexType, + kDeviceRenderTarget_TexType, + kSaveLayerDeviceRenderTarget_TexType + }; + TexCache lockCachedTexture(const SkBitmap& bitmap, + const GrSamplerState* sampler, + TexType type = kBitmap_TexType); + bool isBitmapInTextureCache(const SkBitmap& bitmap, + const GrSamplerState& sampler) const; + void unlockCachedTexture(TexCache); class SkAutoCachedTexture { public: SkAutoCachedTexture(); SkAutoCachedTexture(SkGpuDevice* device, const SkBitmap& bitmap, - const GrSamplerState& sampler, + const GrSamplerState* sampler, GrTexture** texture); ~SkAutoCachedTexture(); - GrTexture* set(SkGpuDevice*, const SkBitmap&, const GrSamplerState&); + GrTexture* set(SkGpuDevice*, const SkBitmap&, const GrSamplerState*); private: SkGpuDevice* fDevice; - TexCache* fTex; + TexCache fTex; }; friend class SkAutoTexCache; + + // overrides from SkDevice + virtual bool onReadPixels(const SkBitmap& bitmap, + int x, int y, + SkCanvas::Config8888 config8888) SK_OVERRIDE; + private: GrContext* fContext; @@ -154,11 +157,14 @@ private: GrSkDrawProcs* fDrawProcs; // state for our offscreen render-target - TexCache* fCache; - GrTexture* fTexture; - GrRenderTarget* fRenderTarget; - bool fNeedClear; - bool fNeedPrepareRenderTarget; + TexCache fCache; + GrTexture* fTexture; + GrRenderTarget* fRenderTarget; + bool fNeedClear; + bool fNeedPrepareRenderTarget; + + // called from rt and tex cons + void initFromRenderTarget(GrContext*, GrRenderTarget*); // doesn't set the texture/sampler/matrix state // caller needs to null out GrPaint's texture if @@ -184,10 +190,20 @@ private: GrPaint* grPaint, bool constantColor); + // override from SkDevice + virtual SkDevice* onCreateCompatibleDevice(SkBitmap::Config config, + int width, int height, + bool isOpaque, + Usage usage); + SkDrawProcs* initDrawForText(GrTextContext*); bool bindDeviceAsTexture(GrPaint* paint); void prepareRenderTarget(const SkDraw&); + bool shouldTileBitmap(const SkBitmap& bitmap, + const GrSamplerState& sampler, + const SkIRect* srcRectPtr, + int* tileSize) const; void internalDrawBitmap(const SkDraw&, const SkBitmap&, const SkIRect&, const SkMatrix&, GrPaint* grPaint); diff --git a/include/gpu/SkGpuDeviceFactory.h b/include/gpu/SkGpuDeviceFactory.h deleted file mode 100644 index 6f62ad6..0000000 --- a/include/gpu/SkGpuDeviceFactory.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - Copyright 2010 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -#ifndef SkGpuDeviceFactory_DEFINED -#define SkGpuDeviceFactory_DEFINED - -#include "SkDevice.h" - -class GrContext; - -class SK_API SkGpuDeviceFactory : public SkDeviceFactory { -public: - /** - * The constructor will ref() the context, passing it to each device - * that it creates. It will be unref()'d in the destructor - * Non-layered devices created by the factory will draw to the - * rootRenderTarget. rootRenderTarget is ref-counted by the factory. - * SkGpuDevice::Current3DApiRenderTarget() can be passed as a special - * value that will cause the factory to create a render target object - * that reflects the state of the underlying 3D API at the time of - * construction. - */ - SkGpuDeviceFactory(GrContext*, GrRenderTarget* rootRenderTarget); - - /** - * When the root layer is both a GrRenderTarget and a GrTexture it - * is handy to have the factory hang on to a ref to the GrTexture object. - * This is because the GrTexture has a ref to the GrRenderTarget but not - * vice-versa. - */ - SkGpuDeviceFactory(GrContext*, GrTexture* rootRenderTargetTexture); - - virtual ~SkGpuDeviceFactory(); - - virtual SkDevice* newDevice(SkCanvas*, SkBitmap::Config, int width, - int height, bool isOpaque, bool isLayer); - -private: - GrContext* fContext; - GrRenderTarget* fRootRenderTarget; - GrTexture* fRootTexture; -}; - -#endif - diff --git a/include/gpu/SkGr.h b/include/gpu/SkGr.h index 65565c9..f4dab53 100644 --- a/include/gpu/SkGr.h +++ b/include/gpu/SkGr.h @@ -1,27 +1,20 @@ -/* - Copyright 2010 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkGr_DEFINED #define SkGr_DEFINED #include <stddef.h> // Gr headers -#include "GrConfig.h" +#include "GrTypes.h" #include "GrContext.h" #include "GrFontScaler.h" #include "GrClipIterator.h" @@ -39,37 +32,9 @@ // #error "inconsistent GR_DEBUG and SK_DEBUG" #endif -#if GR_SCALAR_IS_FIXED - #ifdef SK_SCALAR_IS_FIXED - #define SK_SCALAR_IS_GR_SCALAR 1 - #else - #define SK_SCALAR_IS_GR_SCALAR 0 - #endif - #define SkScalarToGrScalar(x) SkScalarToFixed(x) - -#elif GR_SCALAR_IS_FLOAT - - #ifdef SK_SCALAR_IS_FLOAT - #define SK_SCALAR_IS_GR_SCALAR 1 - #else - #define SK_SCALAR_IS_GR_SCALAR 0 - #endif - #define SkScalarToGrScalar(x) SkScalarToFloat(x) - -#else - #error "Ganesh scalar type not defined" -#endif - //////////////////////////////////////////////////////////////////////////////// // Sk to Gr Type conversions -// Verify that SkPoint and GrPoint are compatible if using the same scalar type -#if 0/*SK_SCALAR_IS_GR_SCALAR*/ - GR_STATIC_ASSERT(sizeof(SkPoint) == sizeof(GrPoint)); - GR_STATIC_ASSERT(offsetof(SkPoint,fX) == offsetof(GrPoint,fX))); - GR_STATIC_ASSERT(offsetof(SkPoint,fY) == offsetof(GrPoint,fY))); -#endif - GR_STATIC_ASSERT((int)GrSamplerState::kClamp_WrapMode == (int)SkShader::kClamp_TileMode); GR_STATIC_ASSERT((int)GrSamplerState::kRepeat_WrapMode ==( int)SkShader::kRepeat_TileMode); @@ -231,10 +196,11 @@ private: //////////////////////////////////////////////////////////////////////////////// // Helper functions -GrTextureEntry* sk_gr_create_bitmap_texture(GrContext* ctx, - GrTextureKey* key, - const GrSamplerState& sampler, - const SkBitmap& bitmap); +static const GrContext::TextureKey gUNCACHED_KEY = ~0; +GrContext::TextureCacheEntry sk_gr_create_bitmap_texture(GrContext* ctx, + GrContext::TextureKey key, + const GrSamplerState* sampler, + const SkBitmap& bitmap); #endif diff --git a/include/gpu/SkGrTexturePixelRef.h b/include/gpu/SkGrTexturePixelRef.h index 5bc64f5..720f130 100644 --- a/include/gpu/SkGrTexturePixelRef.h +++ b/include/gpu/SkGrTexturePixelRef.h @@ -1,53 +1,69 @@ -/* - Copyright 2010 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2010 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkGrTexturePixelRef_DEFINED #define SkGrTexturePixelRef_DEFINED +#include "SkBitmap.h" #include "SkPixelRef.h" -#include "GrGpu.h" +#include "GrTexture.h" +#include "GrRenderTarget.h" + -class SkGrTexturePixelRef : public SkPixelRef { +/** + * Common baseclass that implements onLockPixels() by calling onReadPixels(). + * Since it has a copy, it always returns false for onLockPixelsAreWritable(). + */ +class SkROLockPixelsPixelRef : public SkPixelRef { +public: + SkROLockPixelsPixelRef(); + virtual ~SkROLockPixelsPixelRef(); + +protected: + // override from SkPixelRef + virtual void* onLockPixels(SkColorTable** ptr); + virtual void onUnlockPixels(); + virtual bool onLockPixelsAreWritable() const; // return false; + +private: + SkBitmap fBitmap; + typedef SkPixelRef INHERITED; +}; + +/** + * PixelRef that wraps a GrTexture + */ +class SkGrTexturePixelRef : public SkROLockPixelsPixelRef { public: SkGrTexturePixelRef(GrTexture*); virtual ~SkGrTexturePixelRef(); // override from SkPixelRef - virtual SkGpuTexture* getTexture() { return (SkGpuTexture*)fTexture; } + virtual SkGpuTexture* getTexture(); protected: // override from SkPixelRef - virtual void* onLockPixels(SkColorTable** ptr) { - if (ptr) { - *ptr = NULL; - } - return NULL; - } + virtual bool onReadPixels(SkBitmap* dst, const SkIRect* subset); // override from SkPixelRef - virtual void onUnlockPixels() {} - virtual bool onReadPixels(SkBitmap* dst, const SkIRect* subset); + virtual SkPixelRef* deepCopy(SkBitmap::Config dstConfig) SK_OVERRIDE; private: GrTexture* fTexture; - typedef SkPixelRef INHERITED; + typedef SkROLockPixelsPixelRef INHERITED; }; -class SkGrRenderTargetPixelRef : public SkPixelRef { +/** + * PixelRef that wraps a GrRenderTarget + */ +class SkGrRenderTargetPixelRef : public SkROLockPixelsPixelRef { public: SkGrRenderTargetPixelRef(GrRenderTarget* rt); virtual ~SkGrRenderTargetPixelRef(); @@ -57,20 +73,14 @@ public: protected: // override from SkPixelRef - virtual void* onLockPixels(SkColorTable** ptr) { - if (ptr) { - *ptr = NULL; - } - return NULL; - } + virtual bool onReadPixels(SkBitmap* dst, const SkIRect* subset); // override from SkPixelRef - virtual void onUnlockPixels() {} - virtual bool onReadPixels(SkBitmap* dst, const SkIRect* subset); + virtual SkPixelRef* deepCopy(SkBitmap::Config dstConfig) SK_OVERRIDE; private: GrRenderTarget* fRenderTarget; - typedef SkPixelRef INHERITED; + typedef SkROLockPixelsPixelRef INHERITED; }; #endif diff --git a/include/gpu/SkMesaGLContext.h b/include/gpu/SkMesaGLContext.h new file mode 100644 index 0000000..5c329ff --- /dev/null +++ b/include/gpu/SkMesaGLContext.h @@ -0,0 +1,50 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef SkMesaGLContext_DEFINED +#define SkMesaGLContext_DEFINED + +#include "SkGLContext.h" + +#if SK_MESA + +class SkMesaGLContext : public SkGLContext { +private: + typedef intptr_t Context; + +public: + SkMesaGLContext(); + + virtual ~SkMesaGLContext(); + + virtual void makeCurrent() const SK_OVERRIDE; + + class AutoContextRestore { + public: + AutoContextRestore(); + ~AutoContextRestore(); + + private: + Context fOldContext; + GLint fOldWidth; + GLint fOldHeight; + GLint fOldFormat; + void* fOldImage; + }; + +protected: + virtual const GrGLInterface* createGLContext() SK_OVERRIDE; + virtual void destroyGLContext() SK_OVERRIDE; + +private: + Context fContext; + GrGLubyte *fImage; +}; + +#endif + +#endif diff --git a/include/gpu/SkNativeGLContext.h b/include/gpu/SkNativeGLContext.h new file mode 100644 index 0000000..36461ba --- /dev/null +++ b/include/gpu/SkNativeGLContext.h @@ -0,0 +1,81 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef SkNativeGLContext_DEFINED +#define SkNativeGLContext_DEFINED + +#include "SkGLContext.h" + +#if defined(SK_BUILD_FOR_MAC) + #include <AGL/agl.h> + +#elif defined(SK_BUILD_FOR_ANDROID) + #include <GLES2/gl2.h> + #include <EGL/egl.h> +#elif defined(SK_BUILD_FOR_UNIX) + #include <X11/Xlib.h> + #include <GL/glx.h> +#elif defined(SK_BUILD_FOR_WIN32) + #include <Windows.h> + #include <GL/GL.h> +#endif + +class SkNativeGLContext : public SkGLContext { +public: + SkNativeGLContext(); + + virtual ~SkNativeGLContext(); + + virtual void makeCurrent() const SK_OVERRIDE; + + class AutoContextRestore { + public: + AutoContextRestore(); + ~AutoContextRestore(); + + private: + #if defined(SK_BUILD_FOR_MAC) + AGLContext fOldAGLContext; + #elif defined(SK_BUILD_FOR_UNIX) + GLXContext fOldGLXContext; + Display* fOldDisplay; + GLXDrawable fOldDrawable; + #elif defined(SK_BUILD_FOR_WIN32) + HDC fOldHDC; + HGLRC fOldHGLRC; + #elif defined(SK_BUILD_FOR_ANDROID) + EGLContext fOldEGLContext; + EGLDisplay fOldDisplay; + EGLSurface fOldSurface; + #endif + }; + +protected: + virtual const GrGLInterface* createGLContext() SK_OVERRIDE; + virtual void destroyGLContext() SK_OVERRIDE; + +private: +#if defined(SK_BUILD_FOR_MAC) + AGLContext fContext; +#elif defined(SK_BUILD_FOR_UNIX) + GLXContext fContext; + Display* fDisplay; + Pixmap fPixmap; + GLXPixmap fGlxPixmap; +#elif defined(SK_BUILD_FOR_WIN32) + HWND fWindow; + HDC fDeviceContext; + HGLRC fGlRenderContext; + static ATOM gWC; +#elif defined(SK_BUILD_FOR_ANDROID) + EGLContext fContext; + EGLDisplay fDisplay; + EGLSurface fSurface; +#endif +}; + +#endif diff --git a/include/gpu/SkNullGLContext.h b/include/gpu/SkNullGLContext.h new file mode 100644 index 0000000..9e16cee --- /dev/null +++ b/include/gpu/SkNullGLContext.h @@ -0,0 +1,27 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef SkNullGLContext_DEFINED +#define SkNullGLContext_DEFINED + +#include "SkGLContext.h" + +class SkNullGLContext : public SkGLContext { + +public: + SkNullGLContext() {}; + + virtual void makeCurrent() const SK_OVERRIDE {}; + +protected: + virtual const GrGLInterface* createGLContext() SK_OVERRIDE; + + virtual void destroyGLContext() SK_OVERRIDE {}; +}; + +#endif + diff --git a/include/images/SkBitmapRegionDecoder.h b/include/images/SkBitmapRegionDecoder.h index c039c1b..5c8df3e 100644 --- a/include/images/SkBitmapRegionDecoder.h +++ b/include/images/SkBitmapRegionDecoder.h @@ -1,3 +1,11 @@ +/* + * Copyright 2011 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + #ifndef SkBitmapRegionDecoder_DEFINED #define SkBitmapRegionDecoder_DEFINED diff --git a/include/images/SkFlipPixelRef.h b/include/images/SkFlipPixelRef.h index 3b4e97a..455a3da 100644 --- a/include/images/SkFlipPixelRef.h +++ b/include/images/SkFlipPixelRef.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkFlipPixelRef_DEFINED #define SkFlipPixelRef_DEFINED @@ -63,7 +56,9 @@ public: virtual Factory getFactory() const { return Create; } virtual void flatten(SkFlattenableWriteBuffer&) const; static SkPixelRef* Create(SkFlattenableReadBuffer& buffer); - + + SK_DECLARE_PIXEL_REF_REGISTRAR() + protected: virtual void* onLockPixels(SkColorTable**); virtual void onUnlockPixels(); diff --git a/include/images/SkImageDecoder.h b/include/images/SkImageDecoder.h index 4343d6d..361e1a0 100644 --- a/include/images/SkImageDecoder.h +++ b/include/images/SkImageDecoder.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkImageDecoder_DEFINED #define SkImageDecoder_DEFINED diff --git a/include/images/SkImageEncoder.h b/include/images/SkImageEncoder.h index c56e080..a4831f1 100644 --- a/include/images/SkImageEncoder.h +++ b/include/images/SkImageEncoder.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkImageEncoder_DEFINED #define SkImageEncoder_DEFINED diff --git a/include/images/SkImageRef.h b/include/images/SkImageRef.h index 800f12e..f0f06b6 100644 --- a/include/images/SkImageRef.h +++ b/include/images/SkImageRef.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkImageRef_DEFINED #define SkImageRef_DEFINED diff --git a/include/images/SkImageRef_GlobalPool.h b/include/images/SkImageRef_GlobalPool.h index a9d4dce..909ee71 100644 --- a/include/images/SkImageRef_GlobalPool.h +++ b/include/images/SkImageRef_GlobalPool.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2008 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkImageRef_GlobalPool_DEFINED #define SkImageRef_GlobalPool_DEFINED @@ -30,6 +23,8 @@ public: return Create; } static SkPixelRef* Create(SkFlattenableReadBuffer&); + + SK_DECLARE_PIXEL_REF_REGISTRAR() // API to control the global pool diff --git a/include/images/SkJpegUtility.h b/include/images/SkJpegUtility.h index e9dd977..74f1a21 100644 --- a/include/images/SkJpegUtility.h +++ b/include/images/SkJpegUtility.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2010 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkJpegUtility_DEFINED #define SkJpegUtility_DEFINED diff --git a/include/images/SkMovie.h b/include/images/SkMovie.h index 45962a5..f52a786 100644 --- a/include/images/SkMovie.h +++ b/include/images/SkMovie.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkMovie_DEFINED #define SkMovie_DEFINED diff --git a/include/images/SkPageFlipper.h b/include/images/SkPageFlipper.h index 0d791ee..1a18856 100644 --- a/include/images/SkPageFlipper.h +++ b/include/images/SkPageFlipper.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPageFlipper_DEFINED #define SkPageFlipper_DEFINED diff --git a/include/pdf/SkBitSet.h b/include/pdf/SkBitSet.h new file mode 100755 index 0000000..484fc2a --- /dev/null +++ b/include/pdf/SkBitSet.h @@ -0,0 +1,78 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef SkBitSet_DEFINED +#define SkBitSet_DEFINED + +#include "SkTypes.h" +#include "SkTDArray.h" + +class SkBitSet { +public: + /** NumberOfBits must be greater than zero. + */ + explicit SkBitSet(int numberOfBits); + explicit SkBitSet(const SkBitSet& source); + + const SkBitSet& operator=(const SkBitSet& rhs); + bool operator==(const SkBitSet& rhs); + bool operator!=(const SkBitSet& rhs); + + /** Clear all data. + */ + void clearAll(); + + /** Set the value of the index-th bit. + */ + void setBit(int index, bool value); + + /** Test if bit index is set. + */ + bool isBitSet(int index) const; + + /** Or bits from source. false is returned if this doesn't have the same + * bit count as source. + */ + bool orBits(const SkBitSet& source); + + /** Export indices of set bits to T array. + */ + template<typename T> + void exportTo(SkTDArray<T>* array) const { + SkASSERT(array); + uint32_t* data = reinterpret_cast<uint32_t*>(fBitData.get()); + for (unsigned int i = 0; i < fDwordCount; ++i) { + uint32_t value = data[i]; + if (value) { // There are set bits + unsigned int index = i * 32; + for (unsigned int j = 0; j < 32; ++j) { + if (0x1 & (value >> j)) { + array->push(index + j); + } + } + } + } + } + +private: + SkAutoFree fBitData; + // Dword (32-bit) count of the bitset. + size_t fDwordCount; + size_t fBitCount; + + uint32_t* internalGet(int index) const { + SkASSERT((size_t)index < fBitCount); + size_t internalIndex = index / 32; + SkASSERT(internalIndex < fDwordCount); + return reinterpret_cast<uint32_t*>(fBitData.get()) + internalIndex; + } +}; + + +#endif diff --git a/include/pdf/SkPDFCatalog.h b/include/pdf/SkPDFCatalog.h index e02ffa1..68a244f 100644 --- a/include/pdf/SkPDFCatalog.h +++ b/include/pdf/SkPDFCatalog.h @@ -1,24 +1,18 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2010 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFCatalog_DEFINED #define SkPDFCatalog_DEFINED #include <sys/types.h> +#include "SkPDFDocument.h" #include "SkPDFTypes.h" #include "SkRefCnt.h" #include "SkTDArray.h" @@ -32,7 +26,7 @@ class SK_API SkPDFCatalog { public: /** Create a PDF catalog. */ - SkPDFCatalog(); + explicit SkPDFCatalog(SkPDFDocument::Flags flags); ~SkPDFCatalog(); /** Add the passed object to the catalog. Refs obj. @@ -62,6 +56,10 @@ public: */ size_t getObjectNumberSize(SkPDFObject* obj); + /** Return the document flags in effect for this catalog/document. + */ + SkPDFDocument::Flags getDocumentFlags() const { return fDocumentFlags; } + /** Output the cross reference table for objects in the catalog. * Returns the total number of objects. * @param stream The writable output stream to send the output to. @@ -70,6 +68,26 @@ public: */ int32_t emitXrefTable(SkWStream* stream, bool firstPage); + /** Set substitute object for the passed object. + */ + void setSubstitute(SkPDFObject* original, SkPDFObject* substitute); + + /** Find and return any substitute object set for the passed object. If + * there is none, return the passed object. + */ + SkPDFObject* getSubstituteObject(SkPDFObject* object); + + /** Set file offsets for the resources of substitute objects. + * @param fileOffset Accumulated offset of current document. + * @param firstPage Indicate whether this is for the first page only. + * @return Total size of resources of substitute objects. + */ + off_t setSubstituteResourcesOffsets(off_t fileOffset, bool firstPage); + + /** Emit the resources of substitute objects. + */ + void emitSubstituteResources(SkWStream* stream, bool firstPage); + private: struct Rec { Rec(SkPDFObject* object, bool onFirstPage) @@ -84,9 +102,22 @@ private: bool fOnFirstPage; }; - // TODO(vandebo) Make this a hash if it's a performance problem. + struct SubstituteMapping { + SubstituteMapping(SkPDFObject* original, SkPDFObject* substitute) + : fOriginal(original), fSubstitute(substitute) { + } + SkPDFObject* fOriginal; + SkPDFObject* fSubstitute; + }; + + // TODO(vandebo): Make this a hash if it's a performance problem. SkTDArray<struct Rec> fCatalog; + // TODO(arthurhsu): Make this a hash if it's a performance problem. + SkTDArray<SubstituteMapping> fSubstituteMap; + SkTDArray<SkPDFObject*> fSubstituteResourcesFirstPage; + SkTDArray<SkPDFObject*> fSubstituteResourcesRemaining; + // Number of objects on the first page. uint32_t fFirstPageCount; // Next object number to assign (on page > 1). @@ -94,9 +125,13 @@ private: // Next object number to assign on the first page. uint32_t fNextFirstPageObjNum; + SkPDFDocument::Flags fDocumentFlags; + int findObjectIndex(SkPDFObject* obj) const; int assignObjNum(SkPDFObject* obj); + + SkTDArray<SkPDFObject*>* getSubstituteList(bool firstPage); }; #endif diff --git a/include/pdf/SkPDFDevice.h b/include/pdf/SkPDFDevice.h index 6e4d8db..4551149 100644 --- a/include/pdf/SkPDFDevice.h +++ b/include/pdf/SkPDFDevice.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2011 Google Inc. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFDevice_DEFINED #define SkPDFDevice_DEFINED @@ -30,6 +23,7 @@ class SkPDFDevice; class SkPDFDict; class SkPDFFont; class SkPDFFormXObject; +class SkPDFGlyphSetMap; class SkPDFGraphicState; class SkPDFObject; class SkPDFShader; @@ -39,12 +33,6 @@ class SkPDFStream; struct ContentEntry; struct GraphicStateEntry; -class SkPDFDeviceFactory : public SkDeviceFactory { -public: - virtual SkDevice* newDevice(SkCanvas*, SkBitmap::Config, int width, - int height, bool isOpaque, bool isForLayer); -}; - /** \class SkPDFDevice The drawing context for the PDF backend. @@ -65,62 +53,74 @@ public: * a scale+translate transform to move the origin from the * bottom left (PDF default) to the top left. Note2: drawDevice * (used by layer restore) draws the device after this initial - * transform is applied, so the PDF device factory does an + * transform is applied, so the PDF device does an * inverse scale+translate to accommodate the one that SkPDFDevice * always does. */ - // TODO(vandebo) The sizes should be SkSize and not SkISize. + // TODO(vandebo): The sizes should be SkSize and not SkISize. SK_API SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize, const SkMatrix& initialTransform); SK_API virtual ~SkPDFDevice(); - virtual uint32_t getDeviceCapabilities() { return kVector_Capability; } - - virtual void clear(SkColor color); + virtual uint32_t getDeviceCapabilities() SK_OVERRIDE; - virtual bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap) { - return false; - } + virtual void clear(SkColor color) SK_OVERRIDE; /** These are called inside the per-device-layer loop for each draw call. When these are called, we have already applied any saveLayer operations, and are handling any looping from the paint, and any effects from the DrawFilter. */ - virtual void drawPaint(const SkDraw&, const SkPaint& paint); + virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE; virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count, const SkPoint[], - const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; virtual void drawRect(const SkDraw&, const SkRect& r, const SkPaint& paint); virtual void drawPath(const SkDraw&, const SkPath& origpath, const SkPaint& paint, const SkMatrix* prePathMatrix, - bool pathIsMutable); + bool pathIsMutable) SK_OVERRIDE; virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap, const SkIRect* srcRectOrNull, - const SkMatrix& matrix, const SkPaint& paint); + const SkMatrix& matrix, const SkPaint&) SK_OVERRIDE; virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap, int x, int y, - const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; virtual void drawText(const SkDraw&, const void* text, size_t len, - SkScalar x, SkScalar y, const SkPaint& paint); + SkScalar x, SkScalar y, const SkPaint&) SK_OVERRIDE; virtual void drawPosText(const SkDraw&, const void* text, size_t len, const SkScalar pos[], SkScalar constY, - int scalarsPerPos, const SkPaint& paint); + int scalarsPerPos, const SkPaint&) SK_OVERRIDE; virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len, const SkPath& path, const SkMatrix* matrix, - const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount, const SkPoint verts[], const SkPoint texs[], const SkColor colors[], SkXfermode* xmode, const uint16_t indices[], - int indexCount, const SkPaint& paint); + int indexCount, const SkPaint& paint) SK_OVERRIDE; virtual void drawDevice(const SkDraw&, SkDevice*, int x, int y, - const SkPaint&); + const SkPaint&) SK_OVERRIDE; + + enum DrawingArea { + kContent_DrawingArea, // Drawing area for the page content. + kMargin_DrawingArea, // Drawing area for the margin content. + }; + + /** Sets the drawing area for the device. Subsequent draw calls are directed + * to the specific drawing area (margin or content). The default drawing + * area is the content drawing area. + * + * Currently if margin content is drawn and then a complex (for PDF) xfer + * mode is used, like SrcIn, Clear, etc, the margin content will get + * clipped. A simple way to avoid the bug is to always draw the margin + * content last. + */ + SK_API void setDrawingArea(DrawingArea drawingArea); // PDF specific methods. - /** Returns a reference to the resource dictionary for this device. + /** Returns the resource dictionary for this device. */ - SK_API const SkRefPtr<SkPDFDict>& getResourceDict(); + SK_API SkPDFDict* getResourceDict(); /** Get the list of resources (PDF objects) used on this page. * @param resourceList A list to append the resources to. @@ -137,20 +137,34 @@ public: /** Returns a SkStream with the page contents. The caller is responsible for a reference to the returned value. + DEPRECATED: use copyContentToData() */ SK_API SkStream* content() const; + /** Returns a SkStream with the page contents. The caller is responsible + * for calling data->unref() when it is finished. + */ + SK_API SkData* copyContentToData() const; + SK_API const SkMatrix& initialTransform() const { return fInitialTransform; } + /** Returns a SkPDFGlyphSetMap which represents glyph usage of every font + * that shows on this device. + */ + const SkPDFGlyphSetMap& getFontGlyphUsage() const { + return *(fFontGlyphUsage.get()); + } + protected: - // override - virtual SkDeviceFactory* onNewDeviceFactory(); + virtual bool onReadPixels(const SkBitmap& bitmap, int x, int y, + SkCanvas::Config8888) SK_OVERRIDE; + + virtual bool allowImageFilter(SkImageFilter*) SK_OVERRIDE; private: - friend class SkPDFDeviceFactory; - // TODO(vandebo) push most of SkPDFDevice's state into a core object in + // TODO(vandebo): push most of SkPDFDevice's state into a core object in // order to get the right access levels without using friend. friend class ScopedContentEntry; @@ -164,17 +178,33 @@ private: SkTDArray<SkPDFGraphicState*> fGraphicStateResources; SkTDArray<SkPDFObject*> fXObjectResources; SkTDArray<SkPDFFont*> fFontResources; - SkTDArray<SkPDFShader*> fShaderResources; + SkTDArray<SkPDFObject*> fShaderResources; SkTScopedPtr<ContentEntry> fContentEntries; ContentEntry* fLastContentEntry; + SkTScopedPtr<ContentEntry> fMarginContentEntries; + ContentEntry* fLastMarginContentEntry; + DrawingArea fDrawingArea; + + // Accessor and setter functions based on the current DrawingArea. + SkTScopedPtr<ContentEntry>* getContentEntries(); + ContentEntry* getLastContentEntry(); + void setLastContentEntry(ContentEntry* contentEntry); + + // Glyph ids used for each font on this device. + SkTScopedPtr<SkPDFGlyphSetMap> fFontGlyphUsage; - // For use by the DeviceFactory. SkPDFDevice(const SkISize& layerSize, const SkClipStack& existingClipStack, const SkRegion& existingClipRegion); + // override from SkDevice + virtual SkDevice* onCreateCompatibleDevice(SkBitmap::Config config, + int width, int height, + bool isOpaque, + Usage usage) SK_OVERRIDE; + void init(); - void cleanUp(); + void cleanUp(bool clearFontUsage); void createFormXObjectFromDevice(SkRefPtr<SkPDFFormXObject>* xobject); // Clear the passed clip from all existing content entries. @@ -219,6 +249,11 @@ private: const SkIRect* srcRect, const SkPaint& paint); + /** Helper method for copyContentToData. It is responsible for copying the + * list of content entries |entry| to |data|. + */ + void copyContentEntriesToData(ContentEntry* entry, SkWStream* data) const; + // Disable the default copy and assign implementation. SkPDFDevice(const SkPDFDevice&); void operator=(const SkPDFDevice&); diff --git a/include/pdf/SkPDFDocument.h b/include/pdf/SkPDFDocument.h index 0a76ea2..c1c6fb4 100644 --- a/include/pdf/SkPDFDocument.h +++ b/include/pdf/SkPDFDocument.h @@ -1,27 +1,21 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2010 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFDocument_DEFINED #define SkPDFDocument_DEFINED -#include "SkPDFCatalog.h" #include "SkPDFTypes.h" #include "SkRefCnt.h" #include "SkTDArray.h" +#include "SkTScopedPtr.h" +class SkPDFCatalog; class SkPDFDevice; class SkPDFPage; class SkWSteam; @@ -32,35 +26,55 @@ class SkWSteam; */ class SkPDFDocument { public: + enum Flags { + kNoCompression_Flag = 0x01, //!< mask disable stream compression. + kNoEmbedding_Flag = 0x02, //!< mask do not embed fonts. + + kDraftMode_Flags = 0x03, + }; /** Create a PDF document. */ - SK_API SkPDFDocument(); + explicit SK_API SkPDFDocument(Flags flags = (Flags)0); SK_API ~SkPDFDocument(); - /** Output the PDF to the passed stream. + /** Output the PDF to the passed stream. It is an error to call this (it + * will return false and not modify stream) if no pages have been added + * or there are pages missing (i.e. page 1 and 3 have been added, but not + * page 2). + * * @param stream The writable output stream to send the PDF to. */ SK_API bool emitPDF(SkWStream* stream); + /** Sets the specific page to the passed PDF device. If the specified + * page is already set, this overrides it. Returns true if successful. + * Will fail if the document has already been emitted. + * + * @param pageNumber The position to add the passed device (1 based). + * @param pdfDevice The page to add to this document. + */ + SK_API bool setPage(int pageNumber, SkPDFDevice* pdfDevice); + /** Append the passed pdf device to the document as a new page. Returns * true if successful. Will fail if the document has already been emitted. * * @param pdfDevice The page to add to this document. */ - SK_API bool appendPage(const SkRefPtr<SkPDFDevice>& pdfDevice); + SK_API bool appendPage(SkPDFDevice* pdfDevice); /** Get the list of pages in this document. */ SK_API const SkTDArray<SkPDFPage*>& getPages(); private: - SkPDFCatalog fCatalog; + SkTScopedPtr<SkPDFCatalog> fCatalog; int64_t fXRefFileOffset; SkTDArray<SkPDFPage*> fPages; SkTDArray<SkPDFDict*> fPageTree; SkRefPtr<SkPDFDict> fDocCatalog; SkTDArray<SkPDFObject*> fPageResources; + SkTDArray<SkPDFObject*> fSubstitutes; int fSecondPageFirstResourceIndex; SkRefPtr<SkPDFDict> fTrailerDict; diff --git a/include/pdf/SkPDFFont.h b/include/pdf/SkPDFFont.h index 93a72f1..b884017 100644 --- a/include/pdf/SkPDFFont.h +++ b/include/pdf/SkPDFFont.h @@ -1,28 +1,74 @@ + /* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2011 Google Inc. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFFont_DEFINED #define SkPDFFont_DEFINED #include "SkAdvancedTypefaceMetrics.h" +#include "SkBitSet.h" #include "SkPDFTypes.h" #include "SkTDArray.h" #include "SkThread.h" +#include "SkTypeface.h" class SkPaint; +class SkPDFCatalog; +class SkPDFFont; + +class SkPDFGlyphSet : public SkNoncopyable { +public: + SkPDFGlyphSet(); + + void set(const uint16_t* glyphIDs, int numGlyphs); + bool has(uint16_t glyphID) const; + void merge(const SkPDFGlyphSet& usage); + void exportTo(SkTDArray<uint32_t>* glyphIDs) const; + +private: + SkBitSet fBitSet; +}; + +class SkPDFGlyphSetMap : public SkNoncopyable { +public: + struct FontGlyphSetPair { + FontGlyphSetPair(SkPDFFont* font, SkPDFGlyphSet* glyphSet); + + SkPDFFont* fFont; + SkPDFGlyphSet* fGlyphSet; + }; + + SkPDFGlyphSetMap(); + ~SkPDFGlyphSetMap(); + + class F2BIter { + public: + explicit F2BIter(const SkPDFGlyphSetMap& map); + FontGlyphSetPair* next() const; + void reset(const SkPDFGlyphSetMap& map); + + private: + const SkTDArray<FontGlyphSetPair>* fMap; + mutable int fIndex; + }; + + void merge(const SkPDFGlyphSetMap& usage); + void reset(); + + void noteGlyphUsage(SkPDFFont* font, const uint16_t* glyphIDs, + int numGlyphs); + +private: + SkPDFGlyphSet* getGlyphSetForFont(SkPDFFont* font); + + SkTDArray<FontGlyphSetPair> fMap; +}; + /** \class SkPDFFont A PDF Object class representing a font. The font may have resources @@ -45,15 +91,15 @@ public: /** Returns the font type represented in this font. For Type0 fonts, * returns the type of the decendant font. */ - SK_API SkAdvancedTypefaceMetrics::FontType getType(); + SK_API virtual SkAdvancedTypefaceMetrics::FontType getType(); - /** Return true if this font has an encoding for the passed glyph id. + /** Returns true if this font encoding supports glyph IDs above 255. */ - SK_API bool hasGlyph(uint16_t glyphID); + SK_API virtual bool multiByteGlyphs() const = 0; - /** Returns true if this font encoding supports glyph IDs above 255. + /** Return true if this font has an encoding for the passed glyph id. */ - SK_API bool multiByteGlyphs(); + SK_API bool hasGlyph(uint16_t glyphID); /** Convert (in place) the input glyph IDs into the font encoding. If the * font has more glyphs than can be encoded (like a type 1 font with more @@ -73,16 +119,68 @@ public: * @param typeface The typeface to find. * @param glyphID Specify which section of a large font is of interest. */ - SK_API static SkPDFFont* getFontResource(SkTypeface* typeface, + SK_API static SkPDFFont* GetFontResource(SkTypeface* typeface, uint16_t glyphID); + /** Subset the font based on usage set. Returns a SkPDFFont instance with + * subset. + * @param usage Glyph subset requested. + * @return NULL if font does not support subsetting, a new instance + * of SkPDFFont otherwise. + */ + SK_API virtual SkPDFFont* getFontSubset(const SkPDFGlyphSet* usage); + +protected: + // Common constructor to handle common members. + SkPDFFont(SkAdvancedTypefaceMetrics* fontInfo, SkTypeface* typeface, + uint16_t glyphID, bool descendantFont); + + // Accessors for subclass. + SkAdvancedTypefaceMetrics* fontInfo(); + void setFontInfo(SkAdvancedTypefaceMetrics* info); + uint16_t firstGlyphID() const; + uint16_t lastGlyphID() const; + void setLastGlyphID(uint16_t glyphID); + + // Add object to resource list. + void addResource(SkPDFObject* object); + + // Accessors for FontDescriptor associated with this object. + SkPDFDict* getFontDescriptor(); + void setFontDescriptor(SkPDFDict* descriptor); + + // Add common entries to FontDescriptor. + bool addCommonFontDescriptorEntries(int16_t defaultWidth); + + /** Set fFirstGlyphID and fLastGlyphID to span at most 255 glyphs, + * including the passed glyphID. + */ + void adjustGlyphRangeForSingleByteEncoding(int16_t glyphID); + + // Generate ToUnicode table according to glyph usage subset. + // If subset is NULL, all available glyph ids will be used. + void populateToUnicodeTable(const SkPDFGlyphSet* subset); + + // Create instances of derived types based on fontInfo. + static SkPDFFont* Create(SkAdvancedTypefaceMetrics* fontInfo, + SkTypeface* typeface, uint16_t glyphID, + SkPDFDict* fontDescriptor); + + static bool Find(uint32_t fontID, uint16_t glyphID, int* index); + private: + class FontRec { + public: + SkPDFFont* fFont; + uint32_t fFontID; + uint16_t fGlyphID; + + // A fGlyphID of 0 with no fFont always matches. + bool operator==(const FontRec& b) const; + FontRec(SkPDFFont* font, uint32_t fontID, uint16_t fGlyphID); + }; + SkRefPtr<SkTypeface> fTypeface; - SkAdvancedTypefaceMetrics::FontType fType; -#ifdef SK_DEBUG - bool fDescendant; -#endif - bool fMultiByteGlyphs; // The glyph IDs accessible with this font. For Type1 (non CID) fonts, // this will be a subset if the font has more than 255 glyphs. @@ -94,58 +192,11 @@ private: SkTDArray<SkPDFObject*> fResources; SkRefPtr<SkPDFDict> fDescriptor; - class FontRec { - public: - SkPDFFont* fFont; - uint32_t fFontID; - uint16_t fGlyphID; - - // A fGlyphID of 0 with no fFont always matches. - bool operator==(const FontRec& b) const; - FontRec(SkPDFFont* font, uint32_t fontID, uint16_t fGlyphID); - }; + SkAdvancedTypefaceMetrics::FontType fFontType; // This should be made a hash table if performance is a problem. - static SkTDArray<FontRec>& canonicalFonts(); - static SkMutex& canonicalFontsMutex(); - - /** Construct a new font dictionary and support objects. - * @param fontInfo Information about the to create. - * @param typeface The typeface for the font. - * @param glyphID The glyph ID the caller is interested in. This - * is important only for Type1 fonts, which have - * more than 255 glyphs. - * @param descendantFont If this is the descendant (true) or root - * (Type 0 font - false) font dictionary. Only True - * Type and CID encoded fonts will use a true value. - * @param fontDescriptor If the font descriptor has already have generated - * for this font, pass it in here, otherwise pass - * NULL. - */ - SkPDFFont(class SkAdvancedTypefaceMetrics* fontInfo, SkTypeface* typeface, - uint16_t glyphID, bool descendantFont, SkPDFDict* fontDescriptor); - - void populateType0Font(); - void populateCIDFont(); - bool populateType1Font(int16_t glyphID); - - /** Populate the PDF font dictionary as Type3 font which includes glyph - * descriptions with instructions for painting the glyphs. This function - * doesn't use any fields from SkAdvancedTypefaceMetrics (fFontInfo). Font - * information including glyph paths are queried from the platform - * dependent SkGlyphCache. - */ - void populateType3Font(int16_t glyphID); - bool addFontDescriptor(int16_t defaultWidth); - void populateToUnicodeTable(); - void addWidthInfoFromRange(int16_t defaultWidth, - const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry); - /** Set fFirstGlyphID and fLastGlyphID to span at most 255 glyphs, - * including the passed glyphID. - */ - void adjustGlyphRangeForSingleByteEncoding(int16_t glyphID); - - static bool find(uint32_t fontID, uint16_t glyphID, int* index); + static SkTDArray<FontRec>& CanonicalFonts(); + static SkMutex& CanonicalFontsMutex(); }; #endif diff --git a/include/pdf/SkPDFFormXObject.h b/include/pdf/SkPDFFormXObject.h index 41719f0..0c49152 100644 --- a/include/pdf/SkPDFFormXObject.h +++ b/include/pdf/SkPDFFormXObject.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2010 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFFormXObject_DEFINED #define SkPDFFormXObject_DEFINED @@ -36,7 +29,7 @@ class SkPDFCatalog; // The caller could keep track of the form XObjects it creates and // canonicalize them, but the Skia API doesn't provide enough context to // automatically do it (trivially). -class SkPDFFormXObject : public SkPDFObject { +class SkPDFFormXObject : public SkPDFStream { public: /** Create a PDF form XObject. Entries for the dictionary entries are * automatically added. @@ -46,27 +39,9 @@ public: virtual ~SkPDFFormXObject(); // The SkPDFObject interface. - virtual void emitObject(SkWStream* stream, SkPDFCatalog* catalog, - bool indirect); - virtual size_t getOutputSize(SkPDFCatalog* catalog, bool indirect); virtual void getResources(SkTDArray<SkPDFObject*>* resourceList); - /** Add the value to the stream dictionary with the given key. Refs value. - * @param key The key for this dictionary entry. - * @param value The value for this dictionary entry. - * @return The value argument is returned. - */ - SkPDFObject* insert(SkPDFName* key, SkPDFObject* value); - - /** Add the value to the stream dictionary with the given key. Refs value. - * @param key The text of the key for this dictionary entry. - * @param value The value for this dictionary entry. - * @return The value argument is returned. - */ - SkPDFObject* insert(const char key[], SkPDFObject* value); - private: - SkRefPtr<SkPDFStream> fStream; SkTDArray<SkPDFObject*> fResources; }; diff --git a/include/pdf/SkPDFGraphicState.h b/include/pdf/SkPDFGraphicState.h index 49809a4..9420405 100644 --- a/include/pdf/SkPDFGraphicState.h +++ b/include/pdf/SkPDFGraphicState.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2010 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFGraphicState_DEFINED #define SkPDFGraphicState_DEFINED @@ -52,7 +45,7 @@ public: * other references. * @param paint The SkPaint to emulate. */ - static SkPDFGraphicState* getGraphicStateForPaint(const SkPaint& paint); + static SkPDFGraphicState* GetGraphicStateForPaint(const SkPaint& paint); /** Make a graphic state that only sets the passed soft mask. The * reference count of the object is incremented and it is the caller's @@ -60,7 +53,7 @@ public: * @param sMask The form xobject to use as a soft mask. * @param invert Indicates if the alpha of the sMask should be inverted. */ - static SkPDFGraphicState* getSMaskGraphicState(SkPDFFormXObject* sMask, + static SkPDFGraphicState* GetSMaskGraphicState(SkPDFFormXObject* sMask, bool invert); /** Get a graphic state that only unsets the soft mask. The reference @@ -69,7 +62,7 @@ public: * reference pattern used when the returned object is new and has no * other references. */ - static SkPDFGraphicState* getNoSMaskGraphicState(); + static SkPDFGraphicState* GetNoSMaskGraphicState(); private: const SkPaint fPaint; @@ -86,12 +79,14 @@ private: explicit GSCanonicalEntry(SkPDFGraphicState* gs) : fGraphicState(gs), fPaint(&gs->fPaint) {} - explicit GSCanonicalEntry(const SkPaint* paint) : fPaint(paint) {} + explicit GSCanonicalEntry(const SkPaint* paint) + : fGraphicState(NULL), + fPaint(paint) {} }; // This should be made a hash table if performance is a problem. - static SkTDArray<GSCanonicalEntry>& canonicalPaints(); - static SkMutex& canonicalPaintsMutex(); + static SkTDArray<GSCanonicalEntry>& CanonicalPaints(); + static SkMutex& CanonicalPaintsMutex(); SkPDFGraphicState(); explicit SkPDFGraphicState(const SkPaint& paint); @@ -100,7 +95,7 @@ private: static SkPDFObject* GetInvertFunction(); - static int find(const SkPaint& paint); + static int Find(const SkPaint& paint); }; #endif diff --git a/include/pdf/SkPDFImage.h b/include/pdf/SkPDFImage.h index 945ff9e..48b0157 100644 --- a/include/pdf/SkPDFImage.h +++ b/include/pdf/SkPDFImage.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2010 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFImage_DEFINED #define SkPDFImage_DEFINED @@ -34,7 +27,7 @@ struct SkIRect; // We could play the same trick here as is done in SkPDFGraphicState, storing // a copy of the Bitmap object (not the pixels), the pixel generation number, // and settings used from the paint to canonicalize image objects. -class SkPDFImage : public SkPDFObject { +class SkPDFImage : public SkPDFStream { public: /** Create a new Image XObject to represent the passed bitmap. * @param bitmap The image to encode. @@ -56,13 +49,9 @@ public: SkPDFImage* addSMask(SkPDFImage* mask); // The SkPDFObject interface. - virtual void emitObject(SkWStream* stream, SkPDFCatalog* catalog, - bool indirect); - virtual size_t getOutputSize(SkPDFCatalog* catalog, bool indirect); virtual void getResources(SkTDArray<SkPDFObject*>* resourceList); private: - SkRefPtr<SkPDFStream> fStream; SkTDArray<SkPDFObject*> fResources; /** Create a PDF image XObject. Entries for the image properties are @@ -76,20 +65,6 @@ private: */ SkPDFImage(SkStream* imageData, const SkBitmap& bitmap, const SkIRect& srcRect, bool alpha, const SkPaint& paint); - - /** Add the value to the stream dictionary with the given key. Refs value. - * @param key The key for this dictionary entry. - * @param value The value for this dictionary entry. - * @return The value argument is returned. - */ - SkPDFObject* insert(SkPDFName* key, SkPDFObject* value); - - /** Add the value to the stream dictionary with the given key. Refs value. - * @param key The text of the key for this dictionary entry. - * @param value The value for this dictionary entry. - * @return The value argument is returned. - */ - SkPDFObject* insert(const char key[], SkPDFObject* value); }; #endif diff --git a/include/pdf/SkPDFPage.h b/include/pdf/SkPDFPage.h index 0e30028..38a371a 100644 --- a/include/pdf/SkPDFPage.h +++ b/include/pdf/SkPDFPage.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2010 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFPage_DEFINED #define SkPDFPage_DEFINED @@ -37,7 +30,7 @@ public: * have content on it yet. * @param content The page content. */ - explicit SkPDFPage(const SkRefPtr<SkPDFDevice>& content); + explicit SkPDFPage(SkPDFDevice* content); ~SkPDFPage(); /** Before a page and its contents can be sized and emitted, it must @@ -81,7 +74,7 @@ public: * nodes of the pageTree. * @param rootNode An output parameter set to the root node. */ - static void generatePageTree(const SkTDArray<SkPDFPage*>& pages, + static void GeneratePageTree(const SkTDArray<SkPDFPage*>& pages, SkPDFCatalog* catalog, SkTDArray<SkPDFDict*>* pageTree, SkPDFDict** rootNode); @@ -90,6 +83,11 @@ public: */ SK_API const SkTDArray<SkPDFFont*>& getFontResources() const; + /** Returns a SkPDFGlyphSetMap which represents glyph usage of every font + * that shows on this page. + */ + const SkPDFGlyphSetMap& getFontGlyphUsage() const; + private: // Multiple pages may reference the content. SkRefPtr<SkPDFDevice> fDevice; diff --git a/include/pdf/SkPDFShader.h b/include/pdf/SkPDFShader.h index 17f7f03..6b6ae03 100644 --- a/include/pdf/SkPDFShader.h +++ b/include/pdf/SkPDFShader.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2011 Google Inc. * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFShader_DEFINED #define SkPDFShader_DEFINED @@ -32,16 +25,8 @@ class SkPDFCatalog; pattern color space is selected. */ -class SkPDFShader : public SkPDFObject { +class SkPDFShader { public: - virtual ~SkPDFShader(); - - // The SkPDFObject interface. - virtual void emitObject(SkWStream* stream, SkPDFCatalog* catalog, - bool indirect); - virtual size_t getOutputSize(SkPDFCatalog* catalog, bool indirect); - virtual void getResources(SkTDArray<SkPDFObject*>* resourceList); - /** Get the PDF shader for the passed SkShader. If the SkShader is * invalid in some way, returns NULL. The reference count of * the object is incremented and it is the caller's responsibility to @@ -54,57 +39,27 @@ public: * @param surfceBBox The bounding box of the drawing surface (with matrix * already applied). */ - static SkPDFShader* getPDFShader(const SkShader& shader, + static SkPDFObject* GetPDFShader(const SkShader& shader, const SkMatrix& matrix, const SkIRect& surfaceBBox); -private: - class State { - public: - SkShader::GradientType fType; - SkShader::GradientInfo fInfo; - SkAutoFree fColorData; - SkMatrix fCanvasTransform; - SkMatrix fShaderTransform; - SkIRect fBBox; - - SkBitmap fImage; - uint32_t fPixelGeneration; - SkShader::TileMode fImageTileModes[2]; - - explicit State(const SkShader& shader, const SkMatrix& canvasTransform, - const SkIRect& bbox); - bool operator==(const State& b) const; - }; - - SkRefPtr<SkPDFDict> fContent; - SkTDArray<SkPDFObject*> fResources; - SkAutoTDelete<const State> fState; +protected: + class State; class ShaderCanonicalEntry { public: - SkPDFShader* fPDFShader; - const State* fState; + ShaderCanonicalEntry(SkPDFObject* pdfShader, const State* state); + bool operator==(const ShaderCanonicalEntry& b) const; - bool operator==(const ShaderCanonicalEntry& b) const { - return fPDFShader == b.fPDFShader || *fState == *b.fState; - } - ShaderCanonicalEntry(SkPDFShader* pdfShader, const State* state) - : fPDFShader(pdfShader), - fState(state) { - } + SkPDFObject* fPDFShader; + const State* fState; }; // This should be made a hash table if performance is a problem. - static SkTDArray<ShaderCanonicalEntry>& canonicalShaders(); - static SkMutex& canonicalShadersMutex(); - - static SkPDFObject* rangeObject(); - - SkPDFShader(State* state); + static SkTDArray<ShaderCanonicalEntry>& CanonicalShaders(); + static SkMutex& CanonicalShadersMutex(); + static void RemoveShader(SkPDFObject* shader); - void doFunctionShader(); - void doImageShader(); - SkPDFStream* makePSFunction(const SkString& psCode, SkPDFArray* domain); + SkPDFShader(); }; #endif diff --git a/include/pdf/SkPDFStream.h b/include/pdf/SkPDFStream.h index a975ad6..b3a7ad3 100644 --- a/include/pdf/SkPDFStream.h +++ b/include/pdf/SkPDFStream.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2010 Google Inc. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFStream_DEFINED #define SkPDFStream_DEFINED @@ -32,10 +25,17 @@ class SkPDFCatalog; class SkPDFStream : public SkPDFDict { public: /** Create a PDF stream. A Length entry is automatically added to the - * stream dictionary. - * @param stream The data part of the stream. + * stream dictionary. The stream may be retained (stream->ref() may be + * called) so its contents must not be changed after calling this. + * @param data The data part of the stream. */ + explicit SkPDFStream(SkData* data); + /** Deprecated constructor. */ explicit SkPDFStream(SkStream* stream); + /** Create a PDF stream with the same content and dictionary entries + * as the passed one. + */ + explicit SkPDFStream(const SkPDFStream& pdfStream); virtual ~SkPDFStream(); // The SkPDFObject interface. @@ -43,13 +43,33 @@ public: bool indirect); virtual size_t getOutputSize(SkPDFCatalog* catalog, bool indirect); +protected: + /* Create a PDF stream with no data. The setData method must be called to + * set the data. + */ + SkPDFStream(); + + void setData(SkStream* stream); + private: - size_t fLength; - // Only one of the two streams will be valid. - SkRefPtr<SkStream> fPlainData; - SkDynamicMemoryWStream fCompressedData; + enum State { + kUnused_State, //!< The stream hasn't been requested yet. + kNoCompression_State, //!< The stream's been requested in an + // uncompressed form. + kCompressed_State, //!< The stream's already been compressed. + }; + // Indicates what form (or if) the stream has been requested. + State fState; + + // TODO(vandebo): Use SkData (after removing deprecated constructor). + SkRefPtr<SkStream> fData; + SkRefPtr<SkPDFStream> fSubstitute; typedef SkPDFDict INHERITED; + + // Populate the stream dictionary. This method returns false if + // fSubstitute should be used. + bool populate(SkPDFCatalog* catalog); }; #endif diff --git a/include/pdf/SkPDFTypes.h b/include/pdf/SkPDFTypes.h index 6b5146a..155b826 100644 --- a/include/pdf/SkPDFTypes.h +++ b/include/pdf/SkPDFTypes.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2010 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFTypes_DEFINED #define SkPDFTypes_DEFINED @@ -39,15 +32,6 @@ public: SkPDFObject(); virtual ~SkPDFObject(); - /** Subclasses must implement this method to print the object to the - * PDF file. - * @param catalog The object catalog to use. - * @param indirect If true, output an object identifier with the object. - * @param stream The writable output stream to send the output to. - */ - virtual void emitObject(SkWStream* stream, SkPDFCatalog* catalog, - bool indirect) = 0; - /** Return the size (number of bytes) of this object in the final output * file. Compound objects or objects that are computationally intensive * to output should override this method. @@ -65,6 +49,12 @@ public: */ virtual void getResources(SkTDArray<SkPDFObject*>* resourceList); + /** Emit this object unless the catalog has a substitute object, in which + * case emit that. + * @see emitObject + */ + void emit(SkWStream* stream, SkPDFCatalog* catalog, bool indirect); + /** Helper function to output an indirect object. * @param catalog The object catalog to use. * @param stream The writable output stream to send the output to. @@ -75,6 +65,32 @@ public: * @param catalog The object catalog to use. */ size_t getIndirectOutputSize(SkPDFCatalog* catalog); + + /** Static helper function to add a resource to a list. The list takes + * a reference. + * @param resource The resource to add. + * @param list The list to add the resource to. + */ + static void AddResourceHelper(SkPDFObject* resource, + SkTDArray<SkPDFObject*>* list); + + /** Static helper function to copy and reference the resources (and all + * their subresources) into a new list. + * @param resources The resource list. + * @param result The list to add to. + */ + static void GetResourcesHelper(SkTDArray<SkPDFObject*>* resources, + SkTDArray<SkPDFObject*>* result); + +protected: + /** Subclasses must implement this method to print the object to the + * PDF file. + * @param catalog The object catalog to use. + * @param indirect If true, output an object identifier with the object. + * @param stream The writable output stream to send the output to. + */ + virtual void emitObject(SkWStream* stream, SkPDFCatalog* catalog, + bool indirect) = 0; }; /** \class SkPDFObjRef @@ -187,15 +203,15 @@ public: bool indirect); virtual size_t getOutputSize(SkPDFCatalog* catalog, bool indirect); - static SkString formatString(const char* input, size_t len); - static SkString formatString(const uint16_t* input, size_t len, + static SkString FormatString(const char* input, size_t len); + static SkString FormatString(const uint16_t* input, size_t len, bool wideChars); private: static const size_t kMaxLen = 65535; const SkString fValue; - static SkString doFormatString(const void* input, size_t len, + static SkString DoFormatString(const void* input, size_t len, bool wideInput, bool wideOutput); }; @@ -212,6 +228,8 @@ public: explicit SkPDFName(const SkString& name); virtual ~SkPDFName(); + bool operator==(const SkPDFName& b) const; + // The SkPDFObject interface. virtual void emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect); @@ -222,7 +240,7 @@ private: const SkString fValue; - static SkString formatName(const SkString& input); + static SkString FormatName(const SkString& input); }; /** \class SkPDFArray @@ -268,6 +286,21 @@ public: */ SkPDFObject* append(SkPDFObject* value); + /** Creates a SkPDFInt object and appends it to the array. + * @param value The value to add to the array. + */ + void appendInt(int32_t value); + + /** Creates a SkPDFScalar object and appends it to the array. + * @param value The value to add to the array. + */ + void appendScalar(SkScalar value); + + /** Creates a SkPDFName object and appends it to the array. + * @param value The value to add to the array. + */ + void appendName(const char name[]); + private: static const int kMaxLen = 8191; SkTDArray<SkPDFObject*> fValue; @@ -314,18 +347,56 @@ public: */ SkPDFObject* insert(const char key[], SkPDFObject* value); + /** Add the int to the dictionary with the given key. + * @param key The text of the key for this dictionary entry. + * @param value The int value for this dictionary entry. + */ + void insertInt(const char key[], int32_t value); + + /** Add the scalar to the dictionary with the given key. + * @param key The text of the key for this dictionary entry. + * @param value The scalar value for this dictionary entry. + */ + void insertScalar(const char key[], SkScalar value); + + /** Add the name to the dictionary with the given key. + * @param key The text of the key for this dictionary entry. + * @param name The name for this dictionary entry. + */ + void insertName(const char key[], const char name[]); + + /** Add the name to the dictionary with the given key. + * @param key The text of the key for this dictionary entry. + * @param name The name for this dictionary entry. + */ + void insertName(const char key[], const SkString& name) { + this->insertName(key, name.c_str()); + } + /** Remove all entries from the dictionary. */ void clear(); private: - static const int kMaxLen = 4095; - struct Rec { SkPDFName* key; SkPDFObject* value; }; +public: + class Iter { + public: + explicit Iter(const SkPDFDict& dict); + SkPDFName* next(SkPDFObject** value); + + private: + Rec* fIter; + Rec* fStop; + }; + +private: + static const int kMaxLen = 4095; + SkTDArray<struct Rec> fValue; }; diff --git a/include/pdf/SkPDFUtils.h b/include/pdf/SkPDFUtils.h index 50da28c..5b9d74e 100644 --- a/include/pdf/SkPDFUtils.h +++ b/include/pdf/SkPDFUtils.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2011 Google Inc. * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkPDFUtils_DEFINED #define SkPDFUtils_DEFINED @@ -36,7 +29,7 @@ struct SkRect; PRINT_NOT_IMPL("NOT_IMPLEMENTED: " #condition "\n"); \ SkDEBUGCODE(SkASSERT(!assert);) \ } \ - } while(0) + } while (0) class SkPDFUtils { public: diff --git a/include/pipe/SkGPipe.h b/include/pipe/SkGPipe.h index 897766f..29b058e 100644 --- a/include/pipe/SkGPipe.h +++ b/include/pipe/SkGPipe.h @@ -1,20 +1,13 @@ -/* - Copyright 2011 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkGPipe_DEFINED #define SkGPipe_DEFINED @@ -23,6 +16,11 @@ class SkCanvas; +// XLib.h might have defined Status already (ugh) +#ifdef Status + #undef Status +#endif + class SkGPipeReader { public: SkGPipeReader(SkCanvas* target); @@ -31,13 +29,14 @@ public: enum Status { kDone_Status, //!< no more data expected from reader kEOF_Status, //!< need more data from reader - kError_Status //!< encountered error + kError_Status, //!< encountered error + kReadAtom_Status//!< finished reading an atom }; // data must be 4-byte aligned // length must be a multiple of 4 - Status playback(const void* data, size_t length, size_t* bytesRead = NULL); - + Status playback(const void* data, size_t length, size_t* bytesRead = NULL, + bool readAtom = false); private: SkCanvas* fCanvas; class SkGPipeState* fState; diff --git a/include/ports/SkHarfBuzzFont.h b/include/ports/SkHarfBuzzFont.h index b1fce0e..66c5534 100644 --- a/include/ports/SkHarfBuzzFont.h +++ b/include/ports/SkHarfBuzzFont.h @@ -1,31 +1,8 @@ /* - * Copyright (c) 2009, Google Inc. All rights reserved. + * Copyright 2009 Google Inc. * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ #ifndef SkHarfBuzzFont_DEFINED @@ -63,4 +40,3 @@ public: }; #endif - diff --git a/include/ports/SkStream_Win.h b/include/ports/SkStream_Win.h index 1b17450..8496360 100644 --- a/include/ports/SkStream_Win.h +++ b/include/ports/SkStream_Win.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkStream_Win_DEFINED #define SkStream_Win_DEFINED diff --git a/include/ports/SkTypeface_mac.h b/include/ports/SkTypeface_mac.h index 61b226b..eb9d25f 100644 --- a/include/ports/SkTypeface_mac.h +++ b/include/ports/SkTypeface_mac.h @@ -1,26 +1,24 @@ -/* - Copyright 2011 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTypeface_mac_DEFINED #define SkTypeface_mac_DEFINED #include "SkTypeface.h" -#include <Carbon/Carbon.h> +#ifdef SK_BUILD_FOR_MAC +#import <ApplicationServices/ApplicationServices.h> +#endif +#ifdef SK_BUILD_FOR_IOS +#include <CoreText/CoreText.h> +#endif /** * Like the other Typeface create methods, this returns a new reference to the * corresponding typeface for the specified CTFontRef. The caller must call diff --git a/include/ports/SkTypeface_win.h b/include/ports/SkTypeface_win.h index 88678d1..6da843f 100644 --- a/include/ports/SkTypeface_win.h +++ b/include/ports/SkTypeface_win.h @@ -1,20 +1,13 @@ -/* - Copyright 2011 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTypeface_win_DEFINED #define SkTypeface_win_DEFINED @@ -25,7 +18,15 @@ * corresponding typeface for the specified logfont. The caller is responsible * for calling unref() when it is finished. */ -SK_API extern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&); +SK_API SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&); + +/** + * Copy the LOGFONT associated with this typeface into the lf parameter. Note + * that the lfHeight will need to be set afterwards, since the typeface does + * not track this (the paint does). + * typeface may be NULL, in which case we return the logfont for the default font. + */ +SK_API void SkLOGFONTFromTypeface(const SkTypeface* typeface, LOGFONT* lf); #endif diff --git a/include/text/SkTextLayout.h b/include/text/SkTextLayout.h index 2152307..e1e3e56 100644 --- a/include/text/SkTextLayout.h +++ b/include/text/SkTextLayout.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkTextLayout_DEFINED #define SkTextLayout_DEFINED diff --git a/include/utils/SkBoundaryPatch.h b/include/utils/SkBoundaryPatch.h index 835fc3e..9d4b5ad 100644 --- a/include/utils/SkBoundaryPatch.h +++ b/include/utils/SkBoundaryPatch.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkBoundaryPatch_DEFINED #define SkBoundaryPatch_DEFINED diff --git a/include/utils/SkCamera.h b/include/utils/SkCamera.h index 6d76018..57521b8 100644 --- a/include/utils/SkCamera.h +++ b/include/utils/SkCamera.h @@ -1,21 +1,14 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + // Inspired by Rob Johnson's most excellent QuickDraw GX sample code #ifndef SkCamera_DEFINED @@ -157,7 +150,7 @@ public: void rotateY(SkScalar deg); void rotateZ(SkScalar deg); -#ifdef ANDROID +#ifdef SK_BUILD_FOR_ANDROID void setCameraLocation(SkScalar x, SkScalar y, SkScalar z); #endif diff --git a/include/utils/SkCubicInterval.h b/include/utils/SkCubicInterval.h index bd6fc5f..bd1f9b9 100644 --- a/include/utils/SkCubicInterval.h +++ b/include/utils/SkCubicInterval.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkCubicInterval_DEFINED #define SkCubicInterval_DEFINED diff --git a/include/utils/SkCullPoints.h b/include/utils/SkCullPoints.h index cee64e2..9e2c01a 100644 --- a/include/utils/SkCullPoints.h +++ b/include/utils/SkCullPoints.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkCullPoints_DEFINED #define SkCullPoints_DEFINED diff --git a/include/utils/SkDumpCanvas.h b/include/utils/SkDumpCanvas.h index 3731bef..5bfd6f6 100644 --- a/include/utils/SkDumpCanvas.h +++ b/include/utils/SkDumpCanvas.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkDumpCanvas_DEFINED #define SkDumpCanvas_DEFINED @@ -33,7 +40,6 @@ public: kDrawBitmap_Verb, kDrawText_Verb, kDrawPicture_Verb, - kDrawShape_Verb, kDrawVertices_Verb, kDrawData_Verb }; @@ -52,58 +58,53 @@ public: int getNestLevel() const { return fNestLevel; } - // overrides from SkCanvas - - virtual int save(SaveFlags flags = kMatrixClip_SaveFlag); + virtual int save(SaveFlags) SK_OVERRIDE; virtual int saveLayer(const SkRect* bounds, const SkPaint* paint, - SaveFlags flags = kARGB_ClipLayer_SaveFlag); - virtual void restore(); + SaveFlags) SK_OVERRIDE; + virtual void restore() SK_OVERRIDE; - virtual bool translate(SkScalar dx, SkScalar dy); - virtual bool scale(SkScalar sx, SkScalar sy); - virtual bool rotate(SkScalar degrees); - virtual bool skew(SkScalar sx, SkScalar sy); - virtual bool concat(const SkMatrix& matrix); - virtual void setMatrix(const SkMatrix& matrix); + virtual bool translate(SkScalar dx, SkScalar dy) SK_OVERRIDE; + virtual bool scale(SkScalar sx, SkScalar sy) SK_OVERRIDE; + virtual bool rotate(SkScalar degrees) SK_OVERRIDE; + virtual bool skew(SkScalar sx, SkScalar sy) SK_OVERRIDE; + virtual bool concat(const SkMatrix& matrix) SK_OVERRIDE; + virtual void setMatrix(const SkMatrix& matrix) SK_OVERRIDE; - virtual bool clipRect(const SkRect& rect, - SkRegion::Op op = SkRegion::kIntersect_Op); - virtual bool clipPath(const SkPath& path, - SkRegion::Op op = SkRegion::kIntersect_Op); + virtual bool clipRect(const SkRect&, SkRegion::Op, bool) SK_OVERRIDE; + virtual bool clipPath(const SkPath&, SkRegion::Op, bool) SK_OVERRIDE; virtual bool clipRegion(const SkRegion& deviceRgn, - SkRegion::Op op = SkRegion::kIntersect_Op); + SkRegion::Op) SK_OVERRIDE; - virtual void drawPaint(const SkPaint& paint); + virtual void drawPaint(const SkPaint& paint) SK_OVERRIDE; virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[], - const SkPaint& paint); - virtual void drawRect(const SkRect& rect, const SkPaint& paint); - virtual void drawPath(const SkPath& path, const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; + virtual void drawRect(const SkRect& rect, const SkPaint& paint) SK_OVERRIDE; + virtual void drawPath(const SkPath& path, const SkPaint& paint) SK_OVERRIDE; virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, - const SkPaint* paint = NULL); + const SkPaint* paint) SK_OVERRIDE; virtual void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* src, - const SkRect& dst, const SkPaint* paint = NULL); + const SkRect& dst, const SkPaint* paint) SK_OVERRIDE; virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m, - const SkPaint* paint = NULL); + const SkPaint* paint) SK_OVERRIDE; virtual void drawSprite(const SkBitmap& bitmap, int left, int top, - const SkPaint* paint = NULL); + const SkPaint* paint) SK_OVERRIDE; virtual void drawText(const void* text, size_t byteLength, SkScalar x, - SkScalar y, const SkPaint& paint); + SkScalar y, const SkPaint& paint) SK_OVERRIDE; virtual void drawPosText(const void* text, size_t byteLength, - const SkPoint pos[], const SkPaint& paint); + const SkPoint pos[], const SkPaint& paint) SK_OVERRIDE; virtual void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY, - const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; virtual void drawTextOnPath(const void* text, size_t byteLength, const SkPath& path, const SkMatrix* matrix, - const SkPaint& paint); - virtual void drawPicture(SkPicture&); - virtual void drawShape(SkShape*); + const SkPaint& paint) SK_OVERRIDE; + virtual void drawPicture(SkPicture&) SK_OVERRIDE; virtual void drawVertices(VertexMode vmode, int vertexCount, const SkPoint vertices[], const SkPoint texs[], const SkColor colors[], SkXfermode* xmode, const uint16_t indices[], int indexCount, - const SkPaint& paint); - virtual void drawData(const void*, size_t); + const SkPaint& paint) SK_OVERRIDE; + virtual void drawData(const void*, size_t) SK_OVERRIDE; private: Dumper* fDumper; @@ -124,7 +125,7 @@ public: // override from baseclass that does the formatting, and in turn calls // the function pointer that was passed to the constructor virtual void dump(SkDumpCanvas*, SkDumpCanvas::Verb, const char str[], - const SkPaint*); + const SkPaint*) SK_OVERRIDE; private: void (*fProc)(const char*, void*); diff --git a/include/utils/SkEGLContext.h b/include/utils/SkEGLContext.h deleted file mode 100644 index ced31a5..0000000 --- a/include/utils/SkEGLContext.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef SkEGLContext_DEFINED -#define SkEGLContext_DEFINED - -#if defined(SK_MESA) - #include "GL/osmesa.h" -#elif defined(SK_BUILD_FOR_MAC) - #include <AGL/agl.h> -#elif defined(SK_BUILD_FOR_ANDROID) - #include "GLES2/gl2.h" - #include "EGL/egl.h" -#elif defined(SK_BUILD_FOR_UNIX) - #include <X11/Xlib.h> - #include <GL/glx.h> -#elif defined(SK_BUILD_FOR_WIN32) - #include <Windows.h> - #include <GL/GL.h> -#else - -#endif - -/** - * Create an offscreen opengl context - */ -class SkEGLContext { -public: - SkEGLContext(); - ~SkEGLContext(); - - bool init(const int width, const int height); - -private: -#if defined(SK_MESA) - OSMesaContext context; - GLfloat *image; -#elif defined(SK_BUILD_FOR_MAC) - AGLContext context; -#elif defined(SK_BUILD_FOR_ANDROID) - -#elif defined(SK_BUILD_FOR_UNIX) - GLXContext context; - Display *display; - Pixmap pixmap; - GLXPixmap glxPixmap; -#elif defined(SK_BUILD_FOR_WIN32) - HWND fWindow; - HDC fDeviceContext; - HGLRC fGlRenderContext; -#else - -#endif -}; - -#endif diff --git a/include/utils/SkGLCanvas.h b/include/utils/SkGLCanvas.h deleted file mode 100644 index eb99527..0000000 --- a/include/utils/SkGLCanvas.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SkGLCanvas_DEFINED -#define SkGLCanvas_DEFINED - -#include "SkCanvas.h" - -// Deprecated. You should now use SkGLDevice and SkGLDeviceFactory with -// SkCanvas. -class SkGLCanvas : public SkCanvas { -public: - SkGLCanvas(); - - static size_t GetTextureCacheMaxCount(); - static void SetTextureCacheMaxCount(size_t count); - - static size_t GetTextureCacheMaxSize(); - static void SetTextureCacheMaxSize(size_t size); - - static void DeleteAllTextures(); - - static void AbandonAllTextures(); -}; - -#endif diff --git a/include/utils/SkInterpolator.h b/include/utils/SkInterpolator.h index c03eb23..289e886 100644 --- a/include/utils/SkInterpolator.h +++ b/include/utils/SkInterpolator.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkInterpolator_DEFINED #define SkInterpolator_DEFINED diff --git a/include/utils/SkJSON.h b/include/utils/SkJSON.h new file mode 100644 index 0000000..5268af5 --- /dev/null +++ b/include/utils/SkJSON.h @@ -0,0 +1,285 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkJSON_DEFINED +#define SkJSON_DEFINED + +#include "SkTypes.h" + +class SkStream; +class SkString; + +class SkJSON { +public: + enum Type { + kObject, + kArray, + kString, + kInt, + kFloat, + kBool, + }; + + class Array; + + class Object { + private: + struct Slot; + + public: + Object(); + Object(const Object&); + ~Object(); + + /** + * Create a new slot with the specified name and value. The name + * parameter is copied, but ownership of the Object parameter is + * transferred. The Object parameter may be null, but the name must + * not be null. + */ + void addObject(const char name[], Object* value); + + /** + * Create a new slot with the specified name and value. The name + * parameter is copied, but ownership of the Array parameter is + * transferred. The Array parameter may be null, but the name must + * not be null. + */ + void addArray(const char name[], Array* value); + + /** + * Create a new slot with the specified name and value. Both parameters + * are copied. The value parameter may be null, but the name must + * not be null. + */ + void addString(const char name[], const char value[]); + + /** + * Create a new slot with the specified name and value. The name + * parameter is copied, and must not be null. + */ + void addInt(const char name[], int32_t value); + + /** + * Create a new slot with the specified name and value. The name + * parameter is copied, and must not be null. + */ + void addFloat(const char name[], float value); + + /** + * Create a new slot with the specified name and value. The name + * parameter is copied, and must not be null. + */ + void addBool(const char name[], bool value); + + /** + * Return the number of slots/fields in this object. These can be + * iterated using Iter. + */ + int count() const; + + /** + * Returns true if a slot matching the name and Type is found. + */ + bool find(const char name[], Type) const; + bool findObject(const char name[], Object** = NULL) const; + bool findArray(const char name[], Array** = NULL) const; + bool findString(const char name[], SkString* = NULL) const; + bool findInt(const char name[], int32_t* = NULL) const; + bool findFloat(const char name[], float* = NULL) const; + bool findBool(const char name[], bool* = NULL) const; + + /** + * Finds the first slot matching the name and Type and removes it. + * Returns true if found, false if not. + */ + bool remove(const char name[], Type); + + void toDebugf() const; + + /** + * Iterator class which returns all of the fields/slots in an Object, + * in the order that they were added. + */ + class Iter { + public: + Iter(const Object&); + + /** + * Returns true when there are no more entries in the iterator. + * In this case, no other methods should be called. + */ + bool done() const; + + /** + * Moves the iterator to the next element. Should only be called + * if done() returns false. + */ + void next(); + + /** + * Returns the type of the current element. Should only be called + * if done() returns false. + */ + Type type() const; + + /** + * Returns the name of the current element. Should only be called + * if done() returns false. + */ + const char* name() const; + + /** + * Returns the type of the current element. Should only be called + * if done() returns false and type() returns kObject. + */ + Object* objectValue() const; + + /** + * Returns the type of the current element. Should only be called + * if done() returns false and type() returns kArray. + */ + Array* arrayValue() const; + + /** + * Returns the type of the current element. Should only be called + * if done() returns false and type() returns kString. + */ + const char* stringValue() const; + + /** + * Returns the type of the current element. Should only be called + * if done() returns false and type() returns kInt. + */ + int32_t intValue() const; + + /** + * Returns the type of the current element. Should only be called + * if done() returns false and type() returns kFloat. + */ + float floatValue() const; + + /** + * Returns the type of the current element. Should only be called + * if done() returns false and type() returns kBool. + */ + bool boolValue() const; + + private: + Slot* fSlot; + }; + + private: + Slot* fHead; + Slot* fTail; + + const Slot* findSlot(const char name[], Type) const; + Slot* addSlot(Slot*); + void dumpLevel(int level) const; + + friend class Array; + }; + + class Array { + public: + /** + * Creates an array with the specified Type and element count. All + * entries are initialized to NULL/0/false. + */ + Array(Type, int count); + + /** + * Creates an array of ints, initialized by copying the specified + * values. + */ + Array(const int32_t values[], int count); + + /** + * Creates an array of floats, initialized by copying the specified + * values. + */ + Array(const float values[], int count); + + /** + * Creates an array of bools, initialized by copying the specified + * values. + */ + Array(const bool values[], int count); + + Array(const Array&); + ~Array(); + + int count() const { return fCount; } + Type type() const { return fType; } + + /** + * Replace the element at the specified index with the specified + * Object (which may be null). Ownership of the Object is transferred. + * Should only be called if the Array's type is kObject. + */ + void setObject(int index, Object*); + + /** + * Replace the element at the specified index with the specified + * Array (which may be null). Ownership of the Array is transferred. + * Should only be called if the Array's type is kArray. + */ + void setArray(int index, Array*); + + /** + * Replace the element at the specified index with a copy of the + * specified string (which may be null). Should only be called if the + * Array's type is kString. + */ + void setString(int index, const char str[]); + + Object* const* objects() const { + SkASSERT(kObject == fType); + return fArray.fObjects; + } + Array* const* arrays() const { + SkASSERT(kObject == fType); + return fArray.fArrays; + } + const char* const* strings() const { + SkASSERT(kString == fType); + return fArray.fStrings; + } + int32_t* ints() const { + SkASSERT(kInt == fType); + return fArray.fInts; + } + float* floats() const { + SkASSERT(kFloat == fType); + return fArray.fFloats; + } + bool* bools() const { + SkASSERT(kBool == fType); + return fArray.fBools; + } + + private: + int fCount; + Type fType; + union { + void* fVoids; + Object** fObjects; + Array** fArrays; + char** fStrings; + int32_t* fInts; + float* fFloats; + bool* fBools; + } fArray; + + void init(Type, int count, const void* src); + void dumpLevel(int level) const; + + friend class Object; + }; +}; + +#endif diff --git a/include/utils/SkLayer.h b/include/utils/SkLayer.h index 80a2137..9cba463 100644 --- a/include/utils/SkLayer.h +++ b/include/utils/SkLayer.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2010 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkLayer_DEFINED #define SkLayer_DEFINED diff --git a/include/utils/SkMatrix44.h b/include/utils/SkMatrix44.h new file mode 100644 index 0000000..93140b0 --- /dev/null +++ b/include/utils/SkMatrix44.h @@ -0,0 +1,224 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + + +#ifndef SkMatrix44_DEFINED +#define SkMatrix44_DEFINED + +#include "SkMatrix.h" +#include "SkScalar.h" + +#ifdef SK_MSCALAR_IS_DOUBLE + typedef double SkMScalar; + static inline double SkFloatToMScalar(float x) { + return static_cast<double>(x); + } + static inline float SkMScalarToFloat(double x) { + return static_cast<float>(x); + } + static inline double SkDoubleToMScalar(double x) { + return x; + } + static inline double SkMScalarToDouble(double x) { + return x; + } + static const SkMScalar SK_MScalarPI = 3.141592653589793; +#else + typedef float SkMScalar; + static inline float SkFloatToMScalar(float x) { + return x; + } + static inline float SkMScalarToFloat(float x) { + return x; + } + static inline float SkDoubleToMScalar(double x) { + return static_cast<float>(x); + } + static inline double SkMScalarToDouble(float x) { + return static_cast<double>(x); + } + static const SkMScalar SK_MScalarPI = 3.14159265f; +#endif + +#ifdef SK_SCALAR_IS_FLOAT + #define SkMScalarToScalar SkMScalarToFloat + #define SkScalarToMScalar SkFloatToMScalar +#else + #if SK_MSCALAR_IS_DOUBLE + // we don't have fixed <-> double macros, use double<->scalar macros + #define SkMScalarToScalar SkDoubleToScalar + #define SkScalarToMScalar SkScalarToDouble + #else + #define SkMScalarToScalar SkFloatToFixed + #define SkScalarToMScalar SkFixedToFloat + #endif +#endif + +static const SkMScalar SK_MScalar1 = 1; + +/////////////////////////////////////////////////////////////////////////////// + +struct SkVector4 { + SkScalar fData[4]; + + SkVector4() { + this->set(0, 0, 0, 1); + } + SkVector4(const SkVector4& src) { + memcpy(fData, src.fData, sizeof(fData)); + } + SkVector4(SkScalar x, SkScalar y, SkScalar z, SkScalar w = SK_Scalar1) { + fData[0] = x; + fData[1] = y; + fData[2] = z; + fData[3] = w; + } + + SkVector4& operator=(const SkVector4& src) { + memcpy(fData, src.fData, sizeof(fData)); + return *this; + } + + bool operator==(const SkVector4& v) { + return fData[0] == v.fData[0] && fData[1] == v.fData[1] && + fData[2] == v.fData[2] && fData[3] == v.fData[3]; + } + bool operator!=(const SkVector4& v) { + return !(*this == v); + } + bool equals(SkScalar x, SkScalar y, SkScalar z, SkScalar w = SK_Scalar1) { + return fData[0] == x && fData[1] == y && + fData[2] == z && fData[3] == w; + } + + void set(SkScalar x, SkScalar y, SkScalar z, SkScalar w = SK_Scalar1) { + fData[0] = x; + fData[1] = y; + fData[2] = z; + fData[3] = w; + } +}; + +class SK_API SkMatrix44 { +public: + SkMatrix44(); + SkMatrix44(const SkMatrix44&); + SkMatrix44(const SkMatrix44& a, const SkMatrix44& b); + + SkMatrix44& operator=(const SkMatrix44& src) { + memcpy(this, &src, sizeof(*this)); + return *this; + } + + bool operator==(const SkMatrix44& other) const { + return !memcmp(this, &other, sizeof(*this)); + } + bool operator!=(const SkMatrix44& other) const { + return !!memcmp(this, &other, sizeof(*this)); + } + + SkMatrix44(const SkMatrix&); + SkMatrix44& operator=(const SkMatrix& src); + operator SkMatrix() const; + + SkMScalar get(int row, int col) const; + void set(int row, int col, const SkMScalar& value); + + void asColMajorf(float[]) const; + void asColMajord(double[]) const; + void asRowMajorf(float[]) const; + void asRowMajord(double[]) const; + + bool isIdentity() const; + void setIdentity(); + void reset() { this->setIdentity();} + + void set3x3(SkMScalar m00, SkMScalar m01, SkMScalar m02, + SkMScalar m10, SkMScalar m11, SkMScalar m12, + SkMScalar m20, SkMScalar m21, SkMScalar m22); + + void setTranslate(SkMScalar dx, SkMScalar dy, SkMScalar dz); + void preTranslate(SkMScalar dx, SkMScalar dy, SkMScalar dz); + void postTranslate(SkMScalar dx, SkMScalar dy, SkMScalar dz); + + void setScale(SkMScalar sx, SkMScalar sy, SkMScalar sz); + void preScale(SkMScalar sx, SkMScalar sy, SkMScalar sz); + void postScale(SkMScalar sx, SkMScalar sy, SkMScalar sz); + + void setScale(SkMScalar scale) { + this->setScale(scale, scale, scale); + } + void preScale(SkMScalar scale) { + this->preScale(scale, scale, scale); + } + void postScale(SkMScalar scale) { + this->postScale(scale, scale, scale); + } + + void setRotateDegreesAbout(SkMScalar x, SkMScalar y, SkMScalar z, + SkMScalar degrees) { + this->setRotateAbout(x, y, z, degrees * SK_MScalarPI / 180); + } + + /** Rotate about the vector [x,y,z]. If that vector is not unit-length, + it will be automatically resized. + */ + void setRotateAbout(SkMScalar x, SkMScalar y, SkMScalar z, + SkMScalar radians); + /** Rotate about the vector [x,y,z]. Does not check the length of the + vector, assuming it is unit-length. + */ + void setRotateAboutUnit(SkMScalar x, SkMScalar y, SkMScalar z, + SkMScalar radians); + + void setConcat(const SkMatrix44& a, const SkMatrix44& b); + void preConcat(const SkMatrix44& m) { + this->setConcat(*this, m); + } + void postConcat(const SkMatrix44& m) { + this->setConcat(m, *this); + } + + friend SkMatrix44 operator*(const SkMatrix44& a, const SkMatrix44& b) { + return SkMatrix44(a, b); + } + + /** If this is invertible, return that in inverse and return true. If it is + not invertible, return false and ignore the inverse parameter. + */ + bool invert(SkMatrix44* inverse) const; + + /** Apply the matrix to the src vector, returning the new vector in dst. + It is legal for src and dst to point to the same memory. + */ + void map(const SkScalar src[4], SkScalar dst[4]) const; + void map(SkScalar vec[4]) const { + this->map(vec, vec); + } + + friend SkVector4 operator*(const SkMatrix44& m, const SkVector4& src) { + SkVector4 dst; + m.map(src.fData, dst.fData); + return dst; + } + + void dump() const; + +private: + /* Stored in the same order as opengl: + [3][0] = tx + [3][1] = ty + [3][2] = tz + */ + SkMScalar fMat[4][4]; + + double determinant() const; +}; + +#endif diff --git a/include/utils/SkMeshUtils.h b/include/utils/SkMeshUtils.h index 1235485..c7cdeca 100644 --- a/include/utils/SkMeshUtils.h +++ b/include/utils/SkMeshUtils.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkMeshUtils_DEFINED #define SkMeshUtils_DEFINED diff --git a/include/utils/SkNWayCanvas.h b/include/utils/SkNWayCanvas.h index 03bd6d1..4e39c6b 100644 --- a/include/utils/SkNWayCanvas.h +++ b/include/utils/SkNWayCanvas.h @@ -1,4 +1,11 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkNWayCanvas_DEFINED #define SkNWayCanvas_DEFINED @@ -16,56 +23,53 @@ public: /////////////////////////////////////////////////////////////////////////// // These are forwarded to the N canvases we're referencing - virtual int save(SaveFlags flags = kMatrixClip_SaveFlag); - virtual int saveLayer(const SkRect* bounds, const SkPaint* paint, - SaveFlags flags = kARGB_ClipLayer_SaveFlag); - virtual void restore(); - virtual bool translate(SkScalar dx, SkScalar dy); - virtual bool scale(SkScalar sx, SkScalar sy); - virtual bool rotate(SkScalar degrees); - virtual bool skew(SkScalar sx, SkScalar sy); - virtual bool concat(const SkMatrix& matrix); - virtual void setMatrix(const SkMatrix& matrix); - virtual bool clipRect(const SkRect& rect, - SkRegion::Op op = SkRegion::kIntersect_Op); - virtual bool clipPath(const SkPath& path, - SkRegion::Op op = SkRegion::kIntersect_Op); + virtual int save(SaveFlags) SK_OVERRIDE; + virtual int saveLayer(const SkRect* bounds, const SkPaint*, + SaveFlags) SK_OVERRIDE; + virtual void restore() SK_OVERRIDE; + virtual bool translate(SkScalar dx, SkScalar dy) SK_OVERRIDE; + virtual bool scale(SkScalar sx, SkScalar sy) SK_OVERRIDE; + virtual bool rotate(SkScalar degrees) SK_OVERRIDE; + virtual bool skew(SkScalar sx, SkScalar sy) SK_OVERRIDE; + virtual bool concat(const SkMatrix& matrix) SK_OVERRIDE; + virtual void setMatrix(const SkMatrix& matrix) SK_OVERRIDE; + virtual bool clipRect(const SkRect&, SkRegion::Op, bool) SK_OVERRIDE; + virtual bool clipPath(const SkPath&, SkRegion::Op, bool) SK_OVERRIDE; virtual bool clipRegion(const SkRegion& deviceRgn, - SkRegion::Op op = SkRegion::kIntersect_Op); + SkRegion::Op) SK_OVERRIDE; - virtual void drawPaint(const SkPaint& paint); + virtual void drawPaint(const SkPaint& paint) SK_OVERRIDE; virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[], - const SkPaint& paint); - virtual void drawRect(const SkRect& rect, const SkPaint& paint); - virtual void drawPath(const SkPath& path, const SkPaint& paint); + const SkPaint&) SK_OVERRIDE; + virtual void drawRect(const SkRect& rect, const SkPaint&) SK_OVERRIDE; + virtual void drawPath(const SkPath& path, const SkPaint&) SK_OVERRIDE; virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, - const SkPaint* paint = NULL); + const SkPaint*) SK_OVERRIDE; virtual void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* src, - const SkRect& dst, const SkPaint* paint = NULL); + const SkRect& dst, const SkPaint*) SK_OVERRIDE; virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m, - const SkPaint* paint = NULL); + const SkPaint*) SK_OVERRIDE; virtual void drawSprite(const SkBitmap& bitmap, int left, int top, - const SkPaint* paint = NULL); + const SkPaint*) SK_OVERRIDE; virtual void drawText(const void* text, size_t byteLength, SkScalar x, - SkScalar y, const SkPaint& paint); + SkScalar y, const SkPaint&) SK_OVERRIDE; virtual void drawPosText(const void* text, size_t byteLength, - const SkPoint pos[], const SkPaint& paint); + const SkPoint pos[], const SkPaint&) SK_OVERRIDE; virtual void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY, - const SkPaint& paint); + const SkPaint&) SK_OVERRIDE; virtual void drawTextOnPath(const void* text, size_t byteLength, const SkPath& path, const SkMatrix* matrix, - const SkPaint& paint); - virtual void drawPicture(SkPicture&); - virtual void drawShape(SkShape*); + const SkPaint&) SK_OVERRIDE; + virtual void drawPicture(SkPicture&) SK_OVERRIDE; virtual void drawVertices(VertexMode vmode, int vertexCount, const SkPoint vertices[], const SkPoint texs[], const SkColor colors[], SkXfermode* xmode, const uint16_t indices[], int indexCount, - const SkPaint& paint); + const SkPaint&) SK_OVERRIDE; - virtual SkBounder* setBounder(SkBounder* bounder); - virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter); + virtual SkBounder* setBounder(SkBounder*) SK_OVERRIDE; + virtual SkDrawFilter* setDrawFilter(SkDrawFilter*) SK_OVERRIDE; private: SkTDArray<SkCanvas*> fList; diff --git a/include/utils/SkNinePatch.h b/include/utils/SkNinePatch.h index a655621..b0ea46b 100644 --- a/include/utils/SkNinePatch.h +++ b/include/utils/SkNinePatch.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkNinePatch_DEFINED #define SkNinePatch_DEFINED diff --git a/include/utils/SkParse.h b/include/utils/SkParse.h index 57d040c..7491cd6 100644 --- a/include/utils/SkParse.h +++ b/include/utils/SkParse.h @@ -1,24 +1,16 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkParse_DEFINED #define SkParse_DEFINED #include "SkColor.h" -#include "SkMath.h" class SkParse { public: diff --git a/include/utils/SkParsePaint.h b/include/utils/SkParsePaint.h index d23cd92..b35fcf1 100644 --- a/include/utils/SkParsePaint.h +++ b/include/utils/SkParsePaint.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkParsePaint_DEFINED #define SkParsePaint_DEFINED diff --git a/include/utils/SkParsePath.h b/include/utils/SkParsePath.h index d271f7e..b48c2c5 100644 --- a/include/utils/SkParsePath.h +++ b/include/utils/SkParsePath.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkParsePath_DEFINED #define SkParsePath_DEFINED diff --git a/include/utils/SkProxyCanvas.h b/include/utils/SkProxyCanvas.h index 6e55aa6..e96b9b2 100644 --- a/include/utils/SkProxyCanvas.h +++ b/include/utils/SkProxyCanvas.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkProxyCanvas_DEFINED #define SkProxyCanvas_DEFINED @@ -19,64 +26,56 @@ public: SkCanvas* getProxy() const { return fProxy; } void setProxy(SkCanvas* proxy); - // overrides from SkCanvas - - virtual int save(SaveFlags flags = kMatrixClip_SaveFlag); + virtual int save(SaveFlags flags = kMatrixClip_SaveFlag) SK_OVERRIDE; virtual int saveLayer(const SkRect* bounds, const SkPaint* paint, - SaveFlags flags = kARGB_ClipLayer_SaveFlag); - virtual void restore(); + SaveFlags flags = kARGB_ClipLayer_SaveFlag) SK_OVERRIDE; + virtual void restore() SK_OVERRIDE; - virtual bool translate(SkScalar dx, SkScalar dy); - virtual bool scale(SkScalar sx, SkScalar sy); - virtual bool rotate(SkScalar degrees); - virtual bool skew(SkScalar sx, SkScalar sy); - virtual bool concat(const SkMatrix& matrix); - virtual void setMatrix(const SkMatrix& matrix); + virtual bool translate(SkScalar dx, SkScalar dy) SK_OVERRIDE; + virtual bool scale(SkScalar sx, SkScalar sy) SK_OVERRIDE; + virtual bool rotate(SkScalar degrees) SK_OVERRIDE; + virtual bool skew(SkScalar sx, SkScalar sy) SK_OVERRIDE; + virtual bool concat(const SkMatrix& matrix) SK_OVERRIDE; + virtual void setMatrix(const SkMatrix& matrix) SK_OVERRIDE; - virtual bool clipRect(const SkRect& rect, - SkRegion::Op op = SkRegion::kIntersect_Op); - virtual bool clipPath(const SkPath& path, - SkRegion::Op op = SkRegion::kIntersect_Op); + virtual bool clipRect(const SkRect&, SkRegion::Op, bool) SK_OVERRIDE; + virtual bool clipPath(const SkPath&, SkRegion::Op, bool) SK_OVERRIDE; virtual bool clipRegion(const SkRegion& deviceRgn, - SkRegion::Op op = SkRegion::kIntersect_Op); + SkRegion::Op op = SkRegion::kIntersect_Op) SK_OVERRIDE; - virtual void drawPaint(const SkPaint& paint); + virtual void drawPaint(const SkPaint& paint) SK_OVERRIDE; virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[], - const SkPaint& paint); - virtual void drawRect(const SkRect& rect, const SkPaint& paint); - virtual void drawPath(const SkPath& path, const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; + virtual void drawRect(const SkRect& rect, const SkPaint& paint) SK_OVERRIDE; + virtual void drawPath(const SkPath& path, const SkPaint& paint) SK_OVERRIDE; virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, - const SkPaint* paint = NULL); + const SkPaint* paint = NULL) SK_OVERRIDE; virtual void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* src, - const SkRect& dst, const SkPaint* paint = NULL); + const SkRect& dst, const SkPaint* paint = NULL) SK_OVERRIDE; virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m, - const SkPaint* paint = NULL); + const SkPaint* paint = NULL) SK_OVERRIDE; virtual void drawSprite(const SkBitmap& bitmap, int left, int top, - const SkPaint* paint = NULL); + const SkPaint* paint = NULL) SK_OVERRIDE; virtual void drawText(const void* text, size_t byteLength, SkScalar x, - SkScalar y, const SkPaint& paint); + SkScalar y, const SkPaint& paint) SK_OVERRIDE; virtual void drawPosText(const void* text, size_t byteLength, - const SkPoint pos[], const SkPaint& paint); + const SkPoint pos[], const SkPaint& paint) SK_OVERRIDE; virtual void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY, - const SkPaint& paint); + const SkPaint& paint) SK_OVERRIDE; virtual void drawTextOnPath(const void* text, size_t byteLength, const SkPath& path, const SkMatrix* matrix, - const SkPaint& paint); - virtual void drawPicture(SkPicture&); - virtual void drawShape(SkShape*); + const SkPaint& paint) SK_OVERRIDE; + virtual void drawPicture(SkPicture&) SK_OVERRIDE; virtual void drawVertices(VertexMode vmode, int vertexCount, const SkPoint vertices[], const SkPoint texs[], const SkColor colors[], SkXfermode* xmode, const uint16_t indices[], int indexCount, - const SkPaint& paint); - virtual void drawData(const void* data, size_t length); - - virtual SkBounder* setBounder(SkBounder* bounder); - virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter); + const SkPaint& paint) SK_OVERRIDE; + virtual void drawData(const void* data, size_t length) SK_OVERRIDE; - virtual SkDevice* createDevice(SkBitmap::Config, int width, int height, - bool isOpaque, bool isForLayer); + virtual SkBounder* setBounder(SkBounder* bounder) SK_OVERRIDE; + virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter) SK_OVERRIDE; private: SkCanvas* fProxy; diff --git a/include/utils/SkSfntUtils.h b/include/utils/SkSfntUtils.h index 1d8f74e..69c9c03 100644 --- a/include/utils/SkSfntUtils.h +++ b/include/utils/SkSfntUtils.h @@ -1,4 +1,11 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + #ifndef SkSfntUtils_DEFINED #define SkSfntUtils_DEFINED diff --git a/include/utils/SkTextBox.h b/include/utils/SkTextBox.h index 3471f5b..e3b365d 100644 --- a/include/utils/SkTextBox.h +++ b/include/utils/SkTextBox.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkTextBox_DEFINED #define SkTextBox_DEFINED diff --git a/include/utils/SkUnitMappers.h b/include/utils/SkUnitMappers.h index 51708b6..a14f1af 100644 --- a/include/utils/SkUnitMappers.h +++ b/include/utils/SkUnitMappers.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2008 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkUnitMappers_DEFINED #define SkUnitMappers_DEFINED diff --git a/include/utils/SkWGL.h b/include/utils/SkWGL.h new file mode 100644 index 0000000..8eae5af --- /dev/null +++ b/include/utils/SkWGL.h @@ -0,0 +1,90 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "SkRefCnt.h" + +#ifndef SkWGL_DEFINED +#define SkWGL_DEFINED + +/** + * Working with WGL extensions can be a pain. Among the reasons is that You must + * have a GL context to get the proc addresses, but you want to use the procs to + * create a context in the first place. So you have to create a dummy GL ctx to + * get the proc addresses. + * + * This file helps by providing SkCreateWGLInterface(). It returns a struct of + * function pointers that it initializes. It also has a helper function to query + * for WGL extensions. It handles the fact that wglGetExtensionsString is itself + * an extension. + */ + +#if !defined(WIN32_LEAN_AND_MEAN) + #define WIN32_LEAN_AND_MEAN + #define SK_LOCAL_LEAN_AND_MEAN +#endif +#include <Windows.h> +#if defined(SK_LOCAL_LEAN_AND_MEAN) + #undef WIN32_LEAN_AND_MEAN + #undef SK_LOCAL_LEAN_AND_MEAN +#endif + +#define SK_WGL_DRAW_TO_WINDOW 0x2001 +#define SK_WGL_ACCELERATION 0x2003 +#define SK_WGL_SUPPORT_OPENGL 0x2010 +#define SK_WGL_DOUBLE_BUFFER 0x2011 +#define SK_WGL_COLOR_BITS 0x2014 +#define SK_WGL_ALPHA_BITS 0x201B +#define SK_WGL_STENCIL_BITS 0x2023 +#define SK_WGL_FULL_ACCELERATION 0x2027 +#define SK_WGL_SAMPLE_BUFFERS 0x2041 +#define SK_WGL_SAMPLES 0x2042 +#define SK_WGL_CONTEXT_MAJOR_VERSION 0x2091 +#define SK_WGL_CONTEXT_MINOR_VERSION 0x2092 +#define SK_WGL_CONTEXT_LAYER_PLANE 0x2093 +#define SK_WGL_CONTEXT_FLAGS 0x2094 +#define SK_WGL_CONTEXT_PROFILE_MASK 0x9126 +#define SK_WGL_CONTEXT_DEBUG_BIT 0x0001 +#define SK_WGL_CONTEXT_FORWARD_COMPATIBLE_BIT 0x0002 +#define SK_WGL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define SK_WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define SK_WGL_CONTEXT_ES2_PROFILE_BIT 0x00000004 +#define SK_ERROR_INVALID_VERSION 0x2095 +#define SK_ERROR_INVALID_PROFILE 0x2096 + +class SkWGLExtensions { +public: + SkWGLExtensions(); + /** + * Determines if an extensions is available for a given DC. + * WGL_extensions_string is considered a prerequisite for all other + * extensions. It is necessary to check this before calling other class + * functions. + */ + bool hasExtension(HDC dc, const char* ext) const; + + const char* getExtensionsString(HDC hdc) const; + BOOL choosePixelFormat(HDC hdc, const int*, const FLOAT*, UINT, int*, UINT*) const; + BOOL getPixelFormatAttribiv(HDC, int, int, UINT, const int*, int*) const; + BOOL getPixelFormatAttribfv(HDC hdc, int, int, UINT, const int*, FLOAT*) const; + HGLRC createContextAttribs(HDC, HGLRC, const int *) const; + +private: + typedef const char* (WINAPI *GetExtensionsStringProc)(HDC hdc); + typedef BOOL (WINAPI *ChoosePixelFormatProc)(HDC hdc, const int *, const FLOAT *, UINT, int *, UINT *); + typedef BOOL (WINAPI *GetPixelFormatAttribivProc)(HDC, int, int, UINT, const int*, int*); + typedef BOOL (WINAPI *GetPixelFormatAttribfvProc)(HDC hdc, int, int, UINT, const int*, FLOAT*); + typedef HGLRC (WINAPI *CreateContextAttribsProc)(HDC hDC, HGLRC, const int *); + + GetExtensionsStringProc fGetExtensionsString; + ChoosePixelFormatProc fChoosePixelFormat; + GetPixelFormatAttribfvProc fGetPixelFormatAttribfv; + GetPixelFormatAttribivProc fGetPixelFormatAttribiv; + CreateContextAttribsProc fCreateContextAttribs; +}; + +#endif diff --git a/include/utils/android/AndroidKeyToSkKey.h b/include/utils/android/AndroidKeyToSkKey.h index 7b0a035..6bcb148 100644 --- a/include/utils/android/AndroidKeyToSkKey.h +++ b/include/utils/android/AndroidKeyToSkKey.h @@ -1,23 +1,16 @@ + /* - * Copyright (C) 2011 Skia - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2011 Skia * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef _ANDROID_TO_SKIA_KEYCODES_H #define _ANDROID_TO_SKIA_KEYCODES_H -#include "keycodes.h" +#include "android/keycodes.h" #include "SkKey.h" // Convert an Android keycode to an SkKey. This is an incomplete list, only @@ -32,6 +25,8 @@ SkKey AndroidKeycodeToSkKey(int keycode) { return kUp_SkKey; case AKEYCODE_DPAD_DOWN: return kDown_SkKey; + case AKEYCODE_BACK: + return kBack_SkKey; default: return kNONE_SkKey; } diff --git a/include/utils/ios/SkStream_NSData.h b/include/utils/ios/SkStream_NSData.h new file mode 100755 index 0000000..0829a4f --- /dev/null +++ b/include/utils/ios/SkStream_NSData.h @@ -0,0 +1,41 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef SkStream_NSData_DEFINED +#define SkStream_NSData_DEFINED + +#import <UIKit/UIKit.h> +#include "SkStream.h" + +/** Returns an NSData with a copy of the stream's data. The caller must call + retain if it intends to keep the data object beyond the current stack-frame + (i.e. internally we're calling [NSData dataWithBytes...] + */ +NSData* NSData_dataWithStream(SkStream* stream); + +/** Returns an NSData from the named resource (from main bundle). + The caller must call retain if it intends to keep the data object beyond + the current stack-frame + (i.e. internally we're calling [NSData dataWithContentsOfMappedFile...] + */ +NSData* NSData_dataFromResource(const char name[], const char suffix[]); + +/** Wrap a stream around NSData. + */ +class SkStream_NSData : public SkMemoryStream { +public: + SkStream_NSData(NSData* data); + virtual ~SkStream_NSData(); + + static SkStream_NSData* CreateFromResource(const char name[], + const char suffix[]); + +private: + NSData* fNSData; +}; + +#endif diff --git a/include/utils/mac/SkCGUtils.h b/include/utils/mac/SkCGUtils.h index db67edf..055e24c 100644 --- a/include/utils/mac/SkCGUtils.h +++ b/include/utils/mac/SkCGUtils.h @@ -1,15 +1,25 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkCGUtils_DEFINED #define SkCGUtils_DEFINED #include "SkTypes.h" #ifdef SK_BUILD_FOR_MAC - #include <Carbon/Carbon.h> -#else - #include <CoreGraphics/CoreGraphics.h> +#include <ApplicationServices/ApplicationServices.h> +#endif + +#ifdef SK_BUILD_FOR_IOS +#include <CoreGraphics/CoreGraphics.h> #endif class SkBitmap; +class SkStream; /** * Create an imageref from the specified bitmap using the specified colorspace. @@ -34,4 +44,6 @@ static inline CGImageRef SkCreateCGImageRef(const SkBitmap& bm) { */ void SkCGDrawBitmap(CGContextRef, const SkBitmap&, float x, float y); +bool SkPDFDocumentToBitmap(SkStream* stream, SkBitmap* output); + #endif diff --git a/include/utils/unix/XkeysToSkKeys.h b/include/utils/unix/XkeysToSkKeys.h index 1852d99..30eb97d 100644 --- a/include/utils/unix/XkeysToSkKeys.h +++ b/include/utils/unix/XkeysToSkKeys.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #include "X11/Xlib.h" #include "X11/keysym.h" diff --git a/include/utils/unix/keysym2ucs.h b/include/utils/unix/keysym2ucs.h index 1ae6fe4..255a930 100644 --- a/include/utils/unix/keysym2ucs.h +++ b/include/utils/unix/keysym2ucs.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ /* * This module converts keysym values into the corresponding ISO 10646-1 * (UCS, Unicode) values. diff --git a/include/utils/win/SkAutoCoInitialize.h b/include/utils/win/SkAutoCoInitialize.h new file mode 100644 index 0000000..709fa6b --- /dev/null +++ b/include/utils/win/SkAutoCoInitialize.h @@ -0,0 +1,30 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef SkAutoCo_DEFINED +#define SkAutoCo_DEFINED + +#define WIN32_LEAN_AND_MEAN +#include <Windows.h> +#include "SkTemplates.h" + +/** + * An instance of this class initializes COM on creation + * and closes the COM library on destruction. + */ +class SkAutoCoInitialize : SkNoncopyable { +private: + HRESULT fHR; +public: + SkAutoCoInitialize(); + ~SkAutoCoInitialize(); + bool succeeded(); +}; + +#endif diff --git a/include/utils/win/SkHRESULT.h b/include/utils/win/SkHRESULT.h new file mode 100644 index 0000000..ff596c7 --- /dev/null +++ b/include/utils/win/SkHRESULT.h @@ -0,0 +1,50 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkHRESULT_DEFINED +#define SkHRESULT_DEFINED + +#include "SkTypes.h" + +void SkTraceHR(const char* file, unsigned long line, + HRESULT hr, const char* msg); + +#ifdef SK_DEBUG +#define SK_TRACEHR(_hr, _msg) SkTraceHR(__FILE__, __LINE__, _hr, _msg) +#else +#define SK_TRACEHR(_hr, _msg) _hr +#endif + +#define HR_GENERAL(_ex, _msg, _ret) {\ + HRESULT _hr = _ex;\ + if (FAILED(_hr)) {\ + SK_TRACEHR(_hr, _msg);\ + return _ret;\ + }\ +} + +//@{ +/** +These macros are for reporting HRESULT errors. +The expression will be evaluated. +If the resulting HRESULT SUCCEEDED then execution will continue normally. +If the HRESULT FAILED then the macro will return from the current function. +In variants ending with 'M' the given message will be traced when FAILED. +The HR variants will return the HRESULT when FAILED. +The HRB variants will return false when FAILED. +The HRV variants will simply return when FAILED. +*/ +#define HR(ex) HR_GENERAL(ex, NULL, _hr) +#define HRM(ex, msg) HR_GENERAL(ex, msg, _hr) + +#define HRB(ex) HR_GENERAL(ex, NULL, false) +#define HRBM(ex, msg) HR_GENERAL(ex, msg, false) + +#define HRV(ex) HR_GENERAL(ex, NULL, ) +#define HRVM(ex, msg) HR_GENERAL(ex, msg, ) +//@} +#endif diff --git a/include/utils/win/SkIStream.h b/include/utils/win/SkIStream.h new file mode 100644 index 0000000..b7d0949 --- /dev/null +++ b/include/utils/win/SkIStream.h @@ -0,0 +1,131 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + + +#ifndef SkIStream_DEFINED +#define SkIStream_DEFINED + +#define WIN32_LEAN_AND_MEAN +#include <Windows.h> +#include <ole2.h> + +class SkStream; +class SkWStream; + +/** + * A bare IStream implementation which properly reference counts + * but returns E_NOTIMPL for all ISequentialStream and IStream methods. + */ +class SkBaseIStream : public IStream { +private: + LONG _refcount; + +protected: + explicit SkBaseIStream(); + virtual ~SkBaseIStream(); + +public: + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid + , void ** ppvObject); + virtual ULONG STDMETHODCALLTYPE AddRef(void); + virtual ULONG STDMETHODCALLTYPE Release(void); + + // ISequentialStream Interface +public: + virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead); + + virtual HRESULT STDMETHODCALLTYPE Write(void const* pv + , ULONG cb + , ULONG* pcbWritten); + + // IStream Interface +public: + virtual HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER); + + virtual HRESULT STDMETHODCALLTYPE CopyTo(IStream* + , ULARGE_INTEGER + , ULARGE_INTEGER* + , ULARGE_INTEGER*); + + virtual HRESULT STDMETHODCALLTYPE Commit(DWORD); + + virtual HRESULT STDMETHODCALLTYPE Revert(void); + + virtual HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER + , ULARGE_INTEGER + , DWORD); + + virtual HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER + , ULARGE_INTEGER + , DWORD); + + virtual HRESULT STDMETHODCALLTYPE Clone(IStream **); + + virtual HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove + , DWORD dwOrigin + , ULARGE_INTEGER* lpNewFilePointer); + + virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg + , DWORD grfStatFlag); +}; + +/** + * A minimal read-only IStream implementation which wraps an SkIStream. + */ +class SkIStream : public SkBaseIStream { +private: + SkStream *fSkStream; + bool fUnrefOnRelease; + ULARGE_INTEGER fLocation; + + SkIStream(SkStream* stream, bool unrefOnRelease); + virtual ~SkIStream(); + +public: + HRESULT static CreateFromSkStream(SkStream* stream + , bool unrefOnRelease + , IStream ** ppStream); + + virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead); + + virtual HRESULT STDMETHODCALLTYPE Write(void const* pv + , ULONG cb + , ULONG* pcbWritten); + + virtual HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove + , DWORD dwOrigin + , ULARGE_INTEGER* lpNewFilePointer); + + virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg + , DWORD grfStatFlag); +}; + +/** + * A minimal write-only IStream implementation which wraps an SkWIStream. + */ +class SkWIStream : public SkBaseIStream { +private: + SkWStream *fSkWStream; + + SkWIStream(SkWStream* stream); + virtual ~SkWIStream(); + +public: + HRESULT static CreateFromSkWStream(SkWStream* stream, IStream ** ppStream); + + virtual HRESULT STDMETHODCALLTYPE Write(void const* pv + , ULONG cb + , ULONG* pcbWritten); + + virtual HRESULT STDMETHODCALLTYPE Commit(DWORD); + + virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg + , DWORD grfStatFlag); +}; + +#endif diff --git a/include/utils/win/SkTScopedComPtr.h b/include/utils/win/SkTScopedComPtr.h new file mode 100644 index 0000000..b9be037 --- /dev/null +++ b/include/utils/win/SkTScopedComPtr.h @@ -0,0 +1,64 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#ifndef SkSkTScopedPtr_DEFINED +#define SkSkTScopedPtr_DEFINED + +#include "SkTypes.h" +#include "SkTemplates.h" + +template<typename T> +class SkBlockComRef : public T { +private: + virtual ULONG STDMETHODCALLTYPE AddRef(void) = 0; + virtual ULONG STDMETHODCALLTYPE Release(void) = 0; +}; + +template<typename T> +class SkTScopedComPtr : SkNoncopyable { +private: + T *fPtr; + +public: + explicit SkTScopedComPtr(T *ptr = NULL) : fPtr(ptr) { } + ~SkTScopedComPtr() { + this->reset(); + } + T &operator*() const { return *fPtr; } + SkBlockComRef<T> *operator->() const { + return static_cast<SkBlockComRef<T>*>(fPtr); + } + /** + * Returns the address of the underlying pointer. + * This is dangerous -- it breaks encapsulation and the reference escapes. + * Must only be used on instances currently pointing to NULL, + * and only to initialize the instance. + */ + T **operator&() { SkASSERT(fPtr == NULL); return &fPtr; } + T *get() const { return fPtr; } + void reset() { + if (NULL != this->fPtr) { + this->fPtr->Release(); + this->fPtr = NULL; + } + } + + void swap(SkTScopedComPtr<T>& that) { + T* temp = this->fPtr; + this->fPtr = that.fPtr; + that.fPtr = temp; + } + + T* release() { + T* temp = this->fPtr; + this->fPtr = NULL; + return temp; + } +}; + +#endif diff --git a/include/views/SkApplication.h b/include/views/SkApplication.h index 4c4a4fb..8369f68 100644 --- a/include/views/SkApplication.h +++ b/include/views/SkApplication.h @@ -1,25 +1,18 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkApplication_DEFINED #define SkApplication_DEFINED class SkOSWindow; -extern SkOSWindow* create_sk_window(void* hwnd); +extern SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv); extern void application_init(); extern void application_term(); diff --git a/include/views/SkBGViewArtist.h b/include/views/SkBGViewArtist.h index 1bca42f..869beab 100644 --- a/include/views/SkBGViewArtist.h +++ b/include/views/SkBGViewArtist.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBGViewArtist_DEFINED #define SkBGViewArtist_DEFINED diff --git a/include/views/SkBorderView.h b/include/views/SkBorderView.h index 94ccc1f..02f8725 100644 --- a/include/views/SkBorderView.h +++ b/include/views/SkBorderView.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBorderView_DEFINED #define SkBorderView_DEFINED diff --git a/include/views/SkEvent.h b/include/views/SkEvent.h index f6719d6..b3a07e9 100644 --- a/include/views/SkEvent.h +++ b/include/views/SkEvent.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkEvent_DEFINED #define SkEvent_DEFINED @@ -28,62 +21,111 @@ */ typedef uint32_t SkEventSinkID; -/** \class SkEvent - - SkEvents are used to communicate type-safe information to SkEventSinks. - SkEventSinks (including SkViews) each have a unique ID, which is stored - in an event. This ID is used to target the event once it has been "posted". -*/ +/** + * \class SkEvent + * + * When an event is dispatched from the event queue, it is either sent to + * the eventsink matching the target ID (if not 0), or the target proc is + * called (if not NULL). + */ class SkEvent { public: - /** Default construct, creating an empty event. - */ + /** + * Function pointer that takes an event, returns true if it "handled" it. + */ + typedef bool (*Proc)(const SkEvent& evt); + SkEvent(); - /** Construct a new event with the specified type. - */ - explicit SkEvent(const SkString& type); - /** Construct a new event with the specified type. - */ - explicit SkEvent(const char type[]); - /** Construct a new event by copying the fields from the src event. - */ + explicit SkEvent(const SkString& type, SkEventSinkID = 0); + explicit SkEvent(const char type[], SkEventSinkID = 0); SkEvent(const SkEvent& src); ~SkEvent(); -// /** Return the event's type (will never be null) */ -// const char* getType() const; /** Copy the event's type into the specified SkString parameter */ - void getType(SkString* str) const; + void getType(SkString* str) const; + /** Returns true if the event's type matches exactly the specified type (case sensitive) */ - bool isType(const SkString& str) const; + bool isType(const SkString& str) const; + /** Returns true if the event's type matches exactly the specified type (case sensitive) */ - bool isType(const char type[], size_t len = 0) const; - /** Set the event's type to the specified string. - In XML, use the "type" attribute. - */ - void setType(const SkString&); - /** Set the event's type to the specified string. - In XML, use the "type" attribute. - */ - void setType(const char type[], size_t len = 0); + bool isType(const char type[], size_t len = 0) const; + + /** + * Set the event's type to the specified string. + */ + void setType(const SkString&); + + /** + * Set the event's type to the specified string. + */ + void setType(const char type[], size_t len = 0); + + /** + * Return the target ID, or 0 if there is none. + * + * When an event is dispatched from the event queue, it is either sent to + * the eventsink matching the targetID (if not 0), or the target proc is + * called (if not NULL). + */ + SkEventSinkID getTargetID() const { return fTargetID; } + + /** + * Set the target ID for this event. 0 means none. Calling this will + * automatically clear the targetProc to null. + * + * When an event is dispatched from the event queue, it is either sent to + * the eventsink matching the targetID (if not 0), or the target proc is + * called (if not NULL). + */ + SkEvent* setTargetID(SkEventSinkID targetID) { + fTargetProc = NULL; + fTargetID = targetID; + return this; + } + + /** + * Return the target proc, or NULL if it has none. + * + * When an event is dispatched from the event queue, it is either sent to + * the eventsink matching the targetID (if not 0), or the target proc is + * called (if not NULL). + */ + Proc getTargetProc() const { return fTargetProc; } - /** Return the event's unnamed 32bit field. Default value is 0 */ + /** + * Set the target ID for this event. NULL means none. Calling this will + * automatically clear the targetID to 0. + * + * When an event is dispatched from the event queue, it is either sent to + * the eventsink matching the targetID (if not 0), or the target proc is + * called (if not NULL). + */ + SkEvent* setTargetProc(Proc proc) { + fTargetID = 0; + fTargetProc = proc; + return this; + } + + /** + * Return the event's unnamed 32bit field. Default value is 0 + */ uint32_t getFast32() const { return f32; } - /** Set the event's unnamed 32bit field. In XML, use - the subelement <data fast32=... /> - */ - void setFast32(uint32_t x) { f32 = x; } + + /** + * Set the event's unnamed 32bit field. + */ + void setFast32(uint32_t x) { f32 = x; } /** Return true if the event contains the named 32bit field, and return the field in value (if value is non-null). If there is no matching named field, return false and ignore the value parameter. */ - bool findS32(const char name[], int32_t* value = NULL) const { return fMeta.findS32(name, value); } + bool findS32(const char name[], int32_t* value = NULL) const { return fMeta.findS32(name, value); } /** Return true if the event contains the named SkScalar field, and return the field in value (if value is non-null). If there is no matching named field, return false and ignore the value parameter. */ - bool findScalar(const char name[], SkScalar* value = NULL) const { return fMeta.findScalar(name, value); } + bool findScalar(const char name[], SkScalar* value = NULL) const { return fMeta.findScalar(name, value); } /** Return true if the event contains the named SkScalar field, and return the fields in value[] (if value is non-null), and return the number of SkScalars in count (if count is non-null). If there is no matching named field, return false and ignore the value and count parameters. @@ -96,89 +138,82 @@ public: in value (if value is non-null). If there is no matching named field, return false and ignore the value parameter. */ - bool findPtr(const char name[], void** value) const { return fMeta.findPtr(name, value); } - bool findBool(const char name[], bool* value) const { return fMeta.findBool(name, value); } + bool findPtr(const char name[], void** value) const { return fMeta.findPtr(name, value); } + bool findBool(const char name[], bool* value) const { return fMeta.findBool(name, value); } const void* findData(const char name[], size_t* byteCount = NULL) const { return fMeta.findData(name, byteCount); } /** Returns true if ethe event contains the named 32bit field, and if it equals the specified value */ - bool hasS32(const char name[], int32_t value) const { return fMeta.hasS32(name, value); } + bool hasS32(const char name[], int32_t value) const { return fMeta.hasS32(name, value); } /** Returns true if ethe event contains the named SkScalar field, and if it equals the specified value */ - bool hasScalar(const char name[], SkScalar value) const { return fMeta.hasScalar(name, value); } + bool hasScalar(const char name[], SkScalar value) const { return fMeta.hasScalar(name, value); } /** Returns true if ethe event contains the named string field, and if it equals (using strcmp) the specified value */ - bool hasString(const char name[], const char value[]) const { return fMeta.hasString(name, value); } + bool hasString(const char name[], const char value[]) const { return fMeta.hasString(name, value); } /** Returns true if ethe event contains the named pointer field, and if it equals the specified value */ - bool hasPtr(const char name[], void* value) const { return fMeta.hasPtr(name, value); } - bool hasBool(const char name[], bool value) const { return fMeta.hasBool(name, value); } + bool hasPtr(const char name[], void* value) const { return fMeta.hasPtr(name, value); } + bool hasBool(const char name[], bool value) const { return fMeta.hasBool(name, value); } bool hasData(const char name[], const void* data, size_t byteCount) const { return fMeta.hasData(name, data, byteCount); } /** Add/replace the named 32bit field to the event. In XML use the subelement <data name=... s32=... /> */ - void setS32(const char name[], int32_t value) { fMeta.setS32(name, value); } + void setS32(const char name[], int32_t value) { fMeta.setS32(name, value); } /** Add/replace the named SkScalar field to the event. In XML use the subelement <data name=... scalar=... /> */ - void setScalar(const char name[], SkScalar value) { fMeta.setScalar(name, value); } + void setScalar(const char name[], SkScalar value) { fMeta.setScalar(name, value); } /** Add/replace the named SkScalar[] field to the event. */ SkScalar* setScalars(const char name[], int count, const SkScalar values[] = NULL) { return fMeta.setScalars(name, count, values); } /** Add/replace the named string field to the event. In XML use the subelement <data name=... string=... */ - void setString(const char name[], const SkString& value) { fMeta.setString(name, value.c_str()); } + void setString(const char name[], const SkString& value) { fMeta.setString(name, value.c_str()); } /** Add/replace the named string field to the event. In XML use the subelement <data name=... string=... */ - void setString(const char name[], const char value[]) { fMeta.setString(name, value); } + void setString(const char name[], const char value[]) { fMeta.setString(name, value); } /** Add/replace the named pointer field to the event. There is no XML equivalent for this call */ - void setPtr(const char name[], void* value) { fMeta.setPtr(name, value); } - void setBool(const char name[], bool value) { fMeta.setBool(name, value); } + void setPtr(const char name[], void* value) { fMeta.setPtr(name, value); } + void setBool(const char name[], bool value) { fMeta.setBool(name, value); } void setData(const char name[], const void* data, size_t byteCount) { fMeta.setData(name, data, byteCount); } /** Return the underlying metadata object */ - SkMetaData& getMetaData() { return fMeta; } + SkMetaData& getMetaData() { return fMeta; } /** Return the underlying metadata object */ - const SkMetaData& getMetaData() const { return fMeta; } - - void tron() { SkDEBUGCODE(fDebugTrace = true;) } - void troff() { SkDEBUGCODE(fDebugTrace = false;) } - bool isDebugTrace() const - { -#ifdef SK_DEBUG - return fDebugTrace; -#else - return false; -#endif - } + const SkMetaData& getMetaData() const { return fMeta; } /** Call this to initialize the event from the specified XML node */ - void inflate(const SkDOM&, const SkDOM::Node*); + void inflate(const SkDOM&, const SkDOM::Node*); SkDEBUGCODE(void dump(const char title[] = NULL);) - /** Post the specified event to the event queue, targeting the specified eventsink, with an optional - delay. The event must be dynamically allocated for this. It cannot be a global or on the stack. - After this call, ownership is transfered to the system, so the caller must not retain - the event's ptr. Returns false if the event could not be posted (which means it will have been deleted). - */ - static bool Post(SkEvent* evt, SkEventSinkID targetID, SkMSec delay = 0); - /** Post the specified event to the event queue, targeting the specified eventsink, to be delivered on/after the - specified millisecond time. The event must be dynamically allocated for this. It cannot be a global or on the stack. - After this call, ownership is transfered to the system, so the caller must not retain - the event's ptr. Returns false if the event could not be posted (which means it will have been deleted). - */ - static bool PostTime(SkEvent* evt, SkEventSinkID targetID, SkMSec time); - - /** Helper method for calling SkEvent::PostTime(this, ...), where the caller specifies a delay. - The real "time" will be computed automatically by sampling the clock and adding its value - to delay. - */ - bool post(SkEventSinkID sinkID, SkMSec delay = 0) - { - return SkEvent::Post(this, sinkID, delay); - } + /////////////////////////////////////////////////////////////////////////// - void postTime(SkEventSinkID sinkID, SkMSec time) - { - SkEvent::PostTime(this, sinkID, time); + /** + * Post to the event queue using the event's targetID or target-proc. + * + * The event must be dynamically allocated, as ownership is transferred to + * the event queue. It cannot be allocated on the stack or in a global. + */ + void post() { + return this->postDelay(0); } + + /** + * Post to the event queue using the event's targetID or target-proc and + * the specifed millisecond delay. + * + * The event must be dynamically allocated, as ownership is transferred to + * the event queue. It cannot be allocated on the stack or in a global. + */ + void postDelay(SkMSec delay); + + /** + * Post to the event queue using the event's targetID or target-proc. + * The event will be delivered no sooner than the specified millisecond + * time, as measured by SkTime::GetMSecs(). + * + * The event must be dynamically allocated, as ownership is transferred to + * the event queue. It cannot be allocated on the stack or in a global. + */ + void postTime(SkMSec time); /////////////////////////////////////////////// /** Porting layer must call these functions **/ @@ -188,21 +223,21 @@ public: once before any other event method is called, and should be called after the call to SkGraphics::Init(). */ - static void Init(); + static void Init(); /** Global cleanup function for the SkEvent system. Should be called exactly once after all event methods have been called, and should be called before calling SkGraphics::Term(). */ - static void Term(); + static void Term(); /** Call this to process one event from the queue. If it returns true, there are more events to process. */ - static bool ProcessEvent(); + static bool ProcessEvent(); /** Call this whenever the requested timer has expired (requested by a call to SetQueueTimer). It will post any delayed events whose time as "expired" onto the event queue. It may also call SignalQueueTimer() and SignalNonEmptyQueue(). */ - static void ServiceQueueTimer(); + static void ServiceQueueTimer(); /** Return the number of queued events. note that this value may be obsolete upon return, since another thread may have called ProcessEvent() or @@ -239,17 +274,20 @@ private: SkMetaData fMeta; mutable char* fType; // may be characters with low bit set to know that it is not a pointer uint32_t f32; - SkDEBUGCODE(bool fDebugTrace;) - // these are for our implementation of the event queue + // 'there can be only one' (non-zero) between target-id and target-proc SkEventSinkID fTargetID; + Proc fTargetProc; + + // these are for our implementation of the event queue SkMSec fTime; SkEvent* fNextEvent; // either in the delay or normal event queue - void initialize(const char* type, size_t typeLen); + + void initialize(const char* type, size_t typeLen, SkEventSinkID); static bool Enqueue(SkEvent* evt); static SkMSec EnqueueTime(SkEvent* evt, SkMSec time); - static SkEvent* Dequeue(SkEventSinkID* targetID); + static SkEvent* Dequeue(); static bool QHasEvents(); }; diff --git a/include/views/SkEventSink.h b/include/views/SkEventSink.h index 27a6743..69981fa 100644 --- a/include/views/SkEventSink.h +++ b/include/views/SkEventSink.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkEventSink_DEFINED #define SkEventSink_DEFINED @@ -31,53 +24,66 @@ public: SkEventSink(); virtual ~SkEventSink(); - /** Returns this eventsink's unique ID. Use this to post SkEvents to - this eventsink. - */ + /** + * Returns this eventsink's unique ID. Use this to post SkEvents to + * this eventsink. + */ SkEventSinkID getSinkID() const { return fID; } - /** Call this to pass an event to this object for processing. Returns true if the - event was handled. - */ + /** + * Call this to pass an event to this object for processing. Returns true if the + * event was handled. + */ bool doEvent(const SkEvent&); + /** Returns true if the sink (or one of its subclasses) understands the event as a query. If so, the sink may modify the event to communicate its "answer". */ bool doQuery(SkEvent* query); - /** Add sinkID to the list of listeners, to receive events from calls to sendToListeners() - and postToListeners(). If sinkID already exists in the listener list, no change is made. - */ - void addListenerID(SkEventSinkID sinkID); - /** Copy listeners from one event sink to another, typically from parent to child. - @param from the event sink to copy the listeners from - */ + /** + * Add sinkID to the list of listeners, to receive events from calls to sendToListeners() + * and postToListeners(). If sinkID already exists in the listener list, no change is made. + */ + void addListenerID(SkEventSinkID sinkID); + + /** + * Copy listeners from one event sink to another, typically from parent to child. + * @param from the event sink to copy the listeners from + */ void copyListeners(const SkEventSink& from); - /** Remove sinkID from the list of listeners. If sinkID does not appear in the list, - no change is made. - */ - void removeListenerID(SkEventSinkID); - /** Returns true if there are 1 or more listeners attached to this eventsink - */ - bool hasListeners() const; - /** Posts a copy of evt to each of the eventsinks in the lisener list. - */ - void postToListeners(const SkEvent& evt, SkMSec delay = 0); + + /** + * Remove sinkID from the list of listeners. If sinkID does not appear in the list, + * no change is made. + */ + void removeListenerID(SkEventSinkID); + + /** + * Returns true if there are 1 or more listeners attached to this eventsink + */ + bool hasListeners() const; + + /** + * Posts a copy of evt to each of the eventsinks in the lisener list. + * This ignores the targetID and target proc in evt. + */ + void postToListeners(const SkEvent& evt, SkMSec delay = 0); enum EventResult { kHandled_EventResult, //!< the eventsink returned true from its doEvent method kNotHandled_EventResult, //!< the eventsink returned false from its doEvent method kSinkNotFound_EventResult //!< no matching eventsink was found for the event's getSink(). }; - /** DoEvent handles searching for an eventsink object that matches the targetID. - If one is found, it calls the sink's doEvent method, returning - either kHandled_EventResult or kNotHandled_EventResult. If no matching - eventsink is found, kSinkNotFound_EventResult is returned. - */ - static EventResult DoEvent(const SkEvent&, SkEventSinkID targetID); - /** Returns the matching eventsink, or null if not found - */ + /** + * DoEvent handles dispatching the event to its target ID or proc. + */ + static EventResult DoEvent(const SkEvent&); + + /** + * Returns the matching eventsink, or null if not found + */ static SkEventSink* FindSink(SkEventSinkID); protected: diff --git a/include/views/SkImageView.h b/include/views/SkImageView.h index 57215c9..e179141 100644 --- a/include/views/SkImageView.h +++ b/include/views/SkImageView.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkImageView_DEFINED #define SkImageView_DEFINED diff --git a/include/views/SkKey.h b/include/views/SkKey.h index 3fd5114..4db3108 100644 --- a/include/views/SkKey.h +++ b/include/views/SkKey.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkKey_DEFINED #define SkKey_DEFINED diff --git a/include/views/SkOSMenu.h b/include/views/SkOSMenu.h index 433a601..0c4a619 100644 --- a/include/views/SkOSMenu.h +++ b/include/views/SkOSMenu.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkOSMenu_DEFINED #define SkOSMenu_DEFINED @@ -22,30 +15,165 @@ class SkOSMenu { public: - explicit SkOSMenu(const char title[]); + explicit SkOSMenu(const char title[] = ""); ~SkOSMenu(); - - const char* getTitle() const { return fTitle; } - - void appendItem(const char title[], const char eventType[], int32_t eventData); - - // called by SkOSWindow when it receives an OS menu event - int countItems() const; - const char* getItem(int index, uint32_t* cmdID) const; - - SkEvent* createEvent(uint32_t os_cmd); - -private: - const char* fTitle; - - struct Item { - const char* fTitle; - const char* fEventType; - uint32_t fEventData; - uint32_t fOSCmd; // internal + + /** + * Each of these (except action) has an associated value, which is stored in + * the event payload for the item. + * Each type has a specific type for its value... + * Action : none + * List : int (selected index) + * Segmented : int (selected index) + * Slider : float + * Switch : bool + * TextField : string + * TriState : TriState + * Custom : custom object/value + */ + enum Type { + kAction_Type, + kList_Type, + kSlider_Type, + kSwitch_Type, + kTriState_Type, + kTextField_Type, + kCustom_Type }; - SkTDArray<Item> fItems; + + enum TriState { + kMixedState = -1, + kOffState = 0, + kOnState = 1 + }; + + class Item { + public: + /** + * Auto increments a global to generate an unique ID for each new item + * Note: Thread safe + */ + Item(const char label[], SkOSMenu::Type type, const char slotName[], + SkEvent* evt); + ~Item() { delete fEvent; } + + SkEvent* getEvent() const { return fEvent; } + int getID() const { return fID; } + const char* getLabel() const { return fLabel.c_str(); } + const char* getSlotName() const { return fSlotName.c_str(); } + Type getType() const { return fType; } + void setKeyEquivalent(SkUnichar key) { fKey = key; } + SkUnichar getKeyEquivalent() const { return fKey; } + + /** + * Helper functions for predefined types + */ + void setBool(bool value) const; //For Switch + void setScalar(SkScalar value) const; //For Slider + void setInt(int value) const; //For List + void setTriState(TriState value) const; //For Tristate + void setString(const char value[]) const; //For TextField + + /** + * Post event associated with the menu item to target, any changes to + * the associated event must be made prior to calling this method + */ + void postEvent() const { (new SkEvent(*(fEvent)))->post(); } + private: + int fID; + SkEvent* fEvent; + SkString fLabel; + SkString fSlotName; + Type fType; + SkUnichar fKey; + }; + + void reset(); + const char* getTitle() const { return fTitle.c_str(); } + void setTitle (const char title[]) { fTitle.set(title); } + int getCount() const { return fItems.count(); } + const Item* getItemByID(int itemID) const; + void getItems(const Item* items[]) const; + + /** + * Assign key to the menu item with itemID, will do nothing if there's no + * item with the id given + */ + void assignKeyEquivalentToItem(int itemID, SkUnichar key); + /** + * Call this in a SkView's onHandleChar to trigger any menu items with the + * given key equivalent. If such an item is found, the method will return + * true and its corresponding event will be triggered (default behavior + * defined for switches(toggling), tristates(cycle), and lists(cycle), + * for anything else, the event attached is posted without state changes) + * If no menu item can be matched with the key, false will be returned + */ + bool handleKeyEquivalent(SkUnichar key); + + /** + * The following functions append new items to the menu and returns their + * associated unique id, which can be used to by the client to refer to + * the menu item created and change its state. slotName specifies the string + * identifier of any state/value to be returned in the item's SkEvent object + * NOTE: evt must be dynamically allocated + */ + int appendItem(const char label[], Type type, const char slotName[], + SkEvent* evt); + + /** + * Create predefined items with the given parameters. To be used with the + * other helper functions below to retrive/update state information. + * Note: the helper functions below assume that slotName is UNIQUE for all + * menu items of the same type since it's used to identify the event + */ + int appendAction(const char label[], SkEventSinkID target); + int appendList(const char label[], const char slotName[], + SkEventSinkID target, int defaultIndex, const char[] ...); + int appendSlider(const char label[], const char slotName[], + SkEventSinkID target, SkScalar min, SkScalar max, + SkScalar defaultValue); + int appendSwitch(const char label[], const char slotName[], + SkEventSinkID target, bool defaultState = false); + int appendTriState(const char label[], const char slotName[], + SkEventSinkID target, TriState defaultState = kOffState); + int appendTextField(const char label[], const char slotName[], + SkEventSinkID target, const char placeholder[] = ""); + + + /** + * Helper functions to retrieve information other than the stored value for + * some predefined types + */ + static bool FindListItemCount(const SkEvent& evt, int* count); + /** + * Ensure that the items array can store n SkStrings where n is the count + * extracted using FindListItemCount + */ + static bool FindListItems(const SkEvent& evt, SkString items[]); + static bool FindSliderMin(const SkEvent& evt, SkScalar* min); + static bool FindSliderMax(const SkEvent& evt, SkScalar* max); + + /** + * Returns true if an action with the given label is found, false otherwise + */ + static bool FindAction(const SkEvent& evt, const char label[]); + /** + * The following helper functions will return true if evt is generated from + * a predefined item type and retrieve the corresponding state information. + * They will return false and leave value unchanged if there's a type + * mismatch or slotName is incorrect + */ + static bool FindListIndex(const SkEvent& evt, const char slotName[], int* value); + static bool FindSliderValue(const SkEvent& evt, const char slotName[], SkScalar* value); + static bool FindSwitchState(const SkEvent& evt, const char slotName[], bool* value); + static bool FindTriState(const SkEvent& evt, const char slotName[], TriState* value); + static bool FindText(const SkEvent& evt, const char slotName[], SkString* value); + +private: + SkString fTitle; + SkTDArray<Item*> fItems; + // illegal SkOSMenu(const SkOSMenu&); SkOSMenu& operator=(const SkOSMenu&); diff --git a/include/views/SkOSWindow_Android.h b/include/views/SkOSWindow_Android.h index 38a4cf8..bdce5d0 100644 --- a/include/views/SkOSWindow_Android.h +++ b/include/views/SkOSWindow_Android.h @@ -1,33 +1,30 @@ + /* - * Copyright (C) 2011 Skia - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2011 Skia * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkOSWindow_Android_DEFINED #define SkOSWindow_Android_DEFINED #include "SkWindow.h" -#include "SkEvent.h" + +class SkIRect; class SkOSWindow : public SkWindow { public: SkOSWindow(void*) {} ~SkOSWindow() {} - bool attachGL() { return false; } + bool attachGL() { return true; } void detachGL() {} void presentGL() {} + virtual void onPDFSaved(const char title[], const char desc[], + const char path[]); + protected: // overrides from SkWindow virtual void onHandleInval(const SkIRect&); diff --git a/include/views/SkOSWindow_Mac.h b/include/views/SkOSWindow_Mac.h index 232a202..b09f1dd 100644 --- a/include/views/SkOSWindow_Mac.h +++ b/include/views/SkOSWindow_Mac.h @@ -1,45 +1,28 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ -#ifndef SkOSWindow_Mac_DEFINED -#define SkOSWindow_Mac_DEFINED +#ifndef SkOSWindow_MacCocoa_DEFINED +#define SkOSWindow_MacCocoa_DEFINED -#include <Carbon/Carbon.h> #include "SkWindow.h" class SkOSWindow : public SkWindow { public: SkOSWindow(void* hwnd); - + ~SkOSWindow(); void* getHWND() const { return fHWND; } - void* getHVIEW() const { return fHVIEW; } - void updateSize(); - - static bool PostEvent(SkEvent* evt, SkEventSinkID, SkMSec delay); - - static OSStatus EventHandler(EventHandlerCallRef inHandler, - EventRef inEvent, void* userData); - - void doPaint(void* ctx); - - - bool attachGL(); - void detachGL(); - void presentGL(); - + + virtual bool onDispatchClick(int x, int y, Click::State state, + void* owner); + void detachGL(); + bool attachGL(); + void presentGL(); + protected: // overrides from SkEventSink virtual bool onEvent(const SkEvent& evt); @@ -47,16 +30,15 @@ protected: virtual void onHandleInval(const SkIRect&); // overrides from SkView virtual void onAddMenu(const SkOSMenu*); + virtual void onUpdateMenu(const SkOSMenu*); virtual void onSetTitle(const char[]); - private: void* fHWND; - void* fHVIEW; - void* fAGLCtx; - + bool fInvalEventIsPending; + void* fNotifier; + void* fGLContext; typedef SkWindow INHERITED; }; #endif - diff --git a/include/views/SkOSWindow_SDL.h b/include/views/SkOSWindow_SDL.h index 0ff24f3..037de3b 100644 --- a/include/views/SkOSWindow_SDL.h +++ b/include/views/SkOSWindow_SDL.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkOSWindow_SDL_DEFINED #define SkOSWindow_SDL_DEFINED diff --git a/include/views/SkOSWindow_Unix.h b/include/views/SkOSWindow_Unix.h index 45b53d5..d688fb5 100644 --- a/include/views/SkOSWindow_Unix.h +++ b/include/views/SkOSWindow_Unix.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkOSWindow_Unix_DEFINED #define SkOSWindow_Unix_DEFINED diff --git a/include/views/SkOSWindow_Win.h b/include/views/SkOSWindow_Win.h index 4b3e916..bd6b4bd 100644 --- a/include/views/SkOSWindow_Win.h +++ b/include/views/SkOSWindow_Win.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkOSWindow_Win_DEFINED #define SkOSWindow_Win_DEFINED diff --git a/include/views/SkOSWindow_iOS.h b/include/views/SkOSWindow_iOS.h new file mode 100755 index 0000000..ff28484 --- /dev/null +++ b/include/views/SkOSWindow_iOS.h @@ -0,0 +1,43 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#ifndef SkOSWindow_iOS_DEFINED +#define SkOSWindow_iOS_DEFINED + +#include "SkWindow.h" + +class SkOSWindow : public SkWindow { +public: + SkOSWindow(void* hwnd); + ~SkOSWindow(); + void* getHWND() const { return fHWND; } + + virtual bool onDispatchClick(int x, int y, Click::State state, + void* owner); + void detachGL(); + bool attachGL(); + void presentGL(); + +protected: + // overrides from SkEventSink + virtual bool onEvent(const SkEvent& evt); + // overrides from SkWindow + virtual void onHandleInval(const SkIRect&); + // overrides from SkView + virtual void onAddMenu(const SkOSMenu*); + virtual void onUpdateMenu(const SkOSMenu*); + virtual void onSetTitle(const char[]); + +private: + void* fHWND; + bool fInvalEventIsPending; + void* fNotifier; + typedef SkWindow INHERITED; +}; + +#endif + diff --git a/include/views/SkOSWindow_wxwidgets.h b/include/views/SkOSWindow_wxwidgets.h index c5dfc7c..a662b40 100644 --- a/include/views/SkOSWindow_wxwidgets.h +++ b/include/views/SkOSWindow_wxwidgets.h @@ -1,25 +1,8 @@ /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * SkOSWindow_wxwidgets.h - * wxwidgets - * - * Copyright 2005 __MyCompanyName__. All rights reserved. + * Copyright 2006 The Android Open Source Project * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ #ifndef SkOSWindow_wxwidgets_DEFINED diff --git a/include/views/SkProgressBarView.h b/include/views/SkProgressBarView.h index 6341fcb..0e39d1e 100644 --- a/include/views/SkProgressBarView.h +++ b/include/views/SkProgressBarView.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkProgressBarView_DEFINED #define SkProgressBarView_DEFINED diff --git a/include/views/SkScrollBarView.h b/include/views/SkScrollBarView.h index b8a5209..110d0e1 100644 --- a/include/views/SkScrollBarView.h +++ b/include/views/SkScrollBarView.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkScrollBarView_DEFINED #define SkScrollBarView_DEFINED diff --git a/include/views/SkStackViewLayout.h b/include/views/SkStackViewLayout.h index 8000319..705ff74 100644 --- a/include/views/SkStackViewLayout.h +++ b/include/views/SkStackViewLayout.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkStackViewLayout_DEFINED #define SkStackViewLayout_DEFINED diff --git a/include/views/SkSystemEventTypes.h b/include/views/SkSystemEventTypes.h index 8dfe8be..f0f2952 100644 --- a/include/views/SkSystemEventTypes.h +++ b/include/views/SkSystemEventTypes.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkSystemEventTypes_DEFINED #define SkSystemEventTypes_DEFINED diff --git a/include/views/SkTouchGesture.h b/include/views/SkTouchGesture.h index 79d4e28..527065e 100644 --- a/include/views/SkTouchGesture.h +++ b/include/views/SkTouchGesture.h @@ -1,3 +1,10 @@ + +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ #ifndef SkTouchGesture_DEFINED #define SkTouchGesture_DEFINED diff --git a/include/views/SkView.h b/include/views/SkView.h index d3633db..a5349c2 100644 --- a/include/views/SkView.h +++ b/include/views/SkView.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkView_DEFINED #define SkView_DEFINED @@ -21,6 +14,7 @@ #include "SkRect.h" #include "SkDOM.h" #include "SkTDict.h" +#include "SkMatrix.h" class SkCanvas; class SkLayerView; @@ -87,6 +81,12 @@ public: /** Return a rectangle set to [0, 0, width, height] */ void getLocalBounds(SkRect* bounds) const; + /** Loc - the view's offset with respect to its parent in its view hiearchy. + NOTE: For more complex transforms, use Local Matrix. The tranformations + are applied in the following order: + canvas->translate(fLoc.fX, fLoc.fY); + canvas->concat(fMatrix); + */ /** Return the view's left edge */ SkScalar locX() const { return fLoc.fX; } /** Return the view's top edge */ @@ -96,6 +96,18 @@ public: void setLoc(const SkPoint& loc) { this->setLoc(loc.fX, loc.fY); } void setLocX(SkScalar x) { this->setLoc(x, fLoc.fY); } void setLocY(SkScalar y) { this->setLoc(fLoc.fX, y); } + + /** Local Matrix - matrix used to tranform the view with respect to its + parent in its view hiearchy. Use setLocalMatrix to apply matrix + transformations to the current view and in turn affect its children. + NOTE: For simple offsets, use Loc. The transformations are applied in + the following order: + canvas->translate(fLoc.fX, fLoc.fY); + canvas->concat(fMatrix); + */ + const SkMatrix& getLocalMatrix() const { return fMatrix; } + void setLocalMatrix(const SkMatrix& matrix); + /** Offset (move) the view by the specified dx and dy. This does not affect the view's size */ void offset(SkScalar dx, SkScalar dy); @@ -142,6 +154,7 @@ public: SkPoint fOrig, fPrev, fCurr; SkIPoint fIOrig, fIPrev, fICurr; State fState; + void* fOwner; private: SkEventSinkID fTargetID; char* fType; @@ -168,10 +181,6 @@ public: */ SkView* sendQueryToParents(SkEvent*); - /** Depricated helper function. Just call event->post(sinkID, delay); - */ - bool postEvent(SkEvent* evt, SkEventSinkID sinkID, SkMSec delay) { return evt->post(sinkID, delay); } - // View hierarchy management /** Return the view's parent, or null if it has none. This does not affect the parent's reference count. */ @@ -348,6 +357,7 @@ protected: private: SkScalar fWidth, fHeight; + SkMatrix fMatrix; SkPoint fLoc; SkView* fParent; SkView* fFirstChild; @@ -364,6 +374,8 @@ private: bool setFocusView(SkView* fvOrNull); SkView* acceptFocus(FocusDirection); void detachFromParent_NoLayout(); + /** Compute the matrix to transform view-local coordinates into global ones */ + void localToGlobal(SkMatrix* matrix) const; }; #endif diff --git a/include/views/SkViewInflate.h b/include/views/SkViewInflate.h index 3ec65a6..7282091 100644 --- a/include/views/SkViewInflate.h +++ b/include/views/SkViewInflate.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkViewInflate_DEFINED #define SkViewInflate_DEFINED diff --git a/include/views/SkWidget.h b/include/views/SkWidget.h index db85f01..c3b4530 100644 --- a/include/views/SkWidget.h +++ b/include/views/SkWidget.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkWidget_DEFINED #define SkWidget_DEFINED diff --git a/include/views/SkWidgetViews.h b/include/views/SkWidgetViews.h index 9b3a816..295c101 100644 --- a/include/views/SkWidgetViews.h +++ b/include/views/SkWidgetViews.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkWidgetViews_DEFINED #define SkWidgetViews_DEFINED diff --git a/include/views/SkWindow.h b/include/views/SkWindow.h index fd4ce0a..c72163c 100644 --- a/include/views/SkWindow.h +++ b/include/views/SkWindow.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Copyright 2006 The Android Open Source Project * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkWindow_DEFINED #define SkWindow_DEFINED @@ -54,13 +47,13 @@ public: // return the bounds of the dirty/inval rgn, or [0,0,0,0] if none const SkIRect& getDirtyBounds() const { return fDirtyRgn.getBounds(); } - bool handleClick(int x, int y, Click::State); + bool handleClick(int x, int y, Click::State, void* owner = NULL); bool handleChar(SkUnichar); bool handleKey(SkKey); bool handleKeyUp(SkKey); - bool handleMenu(uint32_t os_cmd); void addMenu(SkOSMenu*); + const SkTDArray<SkOSMenu*>* getMenus() { return &fMenus; } const char* getTitle() const { return fTitle.c_str(); } void setTitle(const char title[]); @@ -70,15 +63,18 @@ public: void preConcat(const SkMatrix&); void postConcat(const SkMatrix&); + virtual void onPDFSaved(const char title[], const char desc[], + const char path[]) {} protected: virtual bool onEvent(const SkEvent&); - virtual bool onDispatchClick(int x, int y, Click::State); + virtual bool onDispatchClick(int x, int y, Click::State, void* owner); // called if part of our bitmap is invalidated virtual void onHandleInval(const SkIRect&); virtual bool onHandleChar(SkUnichar); virtual bool onHandleKey(SkKey); virtual bool onHandleKeyUp(SkKey); - virtual void onAddMenu(const SkOSMenu*) {} + virtual void onAddMenu(const SkOSMenu*) {}; + virtual void onUpdateMenu(const SkOSMenu*) {}; virtual void onSetTitle(const char title[]) {} // overrides from SkView @@ -90,7 +86,8 @@ private: SkBitmap::Config fConfig; SkBitmap fBitmap; SkRegion fDirtyRgn; - Click* fClick; // to track clicks + + SkTDArray<Click*> fClicks; // to track clicks SkTDArray<SkOSMenu*> fMenus; @@ -111,7 +108,7 @@ private: #include "SkOSWindow_Mac.h" #elif defined(SK_BUILD_FOR_WIN) #include "SkOSWindow_Win.h" -#elif defined(ANDROID) +#elif defined(SK_BUILD_FOR_ANDROID) #include "SkOSWindow_Android.h" #elif defined(SK_BUILD_FOR_UNIX) #include "SkOSWindow_Unix.h" diff --git a/include/xml/SkBML_WXMLParser.h b/include/xml/SkBML_WXMLParser.h index faa127d..e16b95c 100644 --- a/include/xml/SkBML_WXMLParser.h +++ b/include/xml/SkBML_WXMLParser.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBML_WXMLParser_DEFINED #define SkBML_WXMLParser_DEFINED diff --git a/include/xml/SkBML_XMLParser.h b/include/xml/SkBML_XMLParser.h index f056bca..7a8d6a1 100644 --- a/include/xml/SkBML_XMLParser.h +++ b/include/xml/SkBML_XMLParser.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkBML_XMLParser_DEFINED #define SkBML_XMLParser_DEFINED diff --git a/include/xml/SkDOM.h b/include/xml/SkDOM.h index 74e2492..60145c8 100644 --- a/include/xml/SkDOM.h +++ b/include/xml/SkDOM.h @@ -1,24 +1,16 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkDOM_DEFINED #define SkDOM_DEFINED #include "SkChunkAlloc.h" -#include "SkMath.h" #include "SkScalar.h" #include "SkTemplates.h" diff --git a/include/xml/SkJS.h b/include/xml/SkJS.h index fe76352..645e03b 100644 --- a/include/xml/SkJS.h +++ b/include/xml/SkJS.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #include "SkTypes.h" #include "SkWindow.h" diff --git a/include/xml/SkXMLParser.h b/include/xml/SkXMLParser.h index 7eccb02..bd8c2f1 100644 --- a/include/xml/SkXMLParser.h +++ b/include/xml/SkXMLParser.h @@ -1,23 +1,15 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkXMLParser_DEFINED #define SkXMLParser_DEFINED -#include "SkMath.h" #include "SkString.h" class SkStream; diff --git a/include/xml/SkXMLWriter.h b/include/xml/SkXMLWriter.h index 742e7f1..4e0eda1 100644 --- a/include/xml/SkXMLWriter.h +++ b/include/xml/SkXMLWriter.h @@ -1,19 +1,12 @@ + /* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Copyright 2006 The Android Open Source Project * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + #ifndef SkXMLWriter_DEFINED #define SkXMLWriter_DEFINED |