2D.h 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  1. /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  2. * This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef _MOZILLA_GFX_2D_H
  6. #define _MOZILLA_GFX_2D_H
  7. #include "Types.h"
  8. #include "Point.h"
  9. #include "Rect.h"
  10. #include "Matrix.h"
  11. #include "Quaternion.h"
  12. #include "UserData.h"
  13. // GenericRefCountedBase allows us to hold on to refcounted objects of any type
  14. // (contrary to RefCounted<T> which requires knowing the type T) and, in particular,
  15. // without having a dependency on that type. This is used for DrawTargetSkia
  16. // to be able to hold on to a GLContext.
  17. #include "mozilla/GenericRefCounted.h"
  18. // This RefPtr class isn't ideal for usage in Azure, as it doesn't allow T**
  19. // outparams using the &-operator. But it will have to do as there's no easy
  20. // solution.
  21. #include "mozilla/RefPtr.h"
  22. #include "mozilla/DebugOnly.h"
  23. #ifdef MOZ_ENABLE_FREETYPE
  24. #include <string>
  25. #endif
  26. #include "gfxPrefs.h"
  27. struct _cairo_surface;
  28. typedef _cairo_surface cairo_surface_t;
  29. struct _cairo_scaled_font;
  30. typedef _cairo_scaled_font cairo_scaled_font_t;
  31. struct _FcPattern;
  32. typedef _FcPattern FcPattern;
  33. struct ID3D11Texture2D;
  34. struct ID3D11Device;
  35. struct ID2D1Device;
  36. struct IDWriteFactory;
  37. struct IDWriteRenderingParams;
  38. struct IDWriteFontFace;
  39. class GrContext;
  40. class SkCanvas;
  41. struct gfxFontStyle;
  42. struct CGContext;
  43. typedef struct CGContext *CGContextRef;
  44. namespace mozilla {
  45. namespace gfx {
  46. class SourceSurface;
  47. class DataSourceSurface;
  48. class DrawTarget;
  49. class DrawEventRecorder;
  50. class FilterNode;
  51. class LogForwarder;
  52. struct NativeSurface {
  53. NativeSurfaceType mType;
  54. SurfaceFormat mFormat;
  55. gfx::IntSize mSize;
  56. void *mSurface;
  57. };
  58. struct NativeFont {
  59. NativeFontType mType;
  60. void *mFont;
  61. };
  62. /**
  63. * This structure is used to send draw options that are universal to all drawing
  64. * operations.
  65. */
  66. struct DrawOptions {
  67. /// For constructor parameter description, see member data documentation.
  68. explicit DrawOptions(Float aAlpha = 1.0f,
  69. CompositionOp aCompositionOp = CompositionOp::OP_OVER,
  70. AntialiasMode aAntialiasMode = AntialiasMode::DEFAULT)
  71. : mAlpha(aAlpha)
  72. , mCompositionOp(aCompositionOp)
  73. , mAntialiasMode(aAntialiasMode)
  74. {}
  75. Float mAlpha; /**< Alpha value by which the mask generated by this
  76. operation is multiplied. */
  77. CompositionOp mCompositionOp; /**< The operator that indicates how the source and
  78. destination patterns are blended. */
  79. AntialiasMode mAntialiasMode; /**< The AntiAlias mode used for this drawing
  80. operation. */
  81. };
  82. /**
  83. * This structure is used to send stroke options that are used in stroking
  84. * operations.
  85. */
  86. struct StrokeOptions {
  87. /// For constructor parameter description, see member data documentation.
  88. explicit StrokeOptions(Float aLineWidth = 1.0f,
  89. JoinStyle aLineJoin = JoinStyle::MITER_OR_BEVEL,
  90. CapStyle aLineCap = CapStyle::BUTT,
  91. Float aMiterLimit = 10.0f,
  92. size_t aDashLength = 0,
  93. const Float* aDashPattern = 0,
  94. Float aDashOffset = 0.f)
  95. : mLineWidth(aLineWidth)
  96. , mMiterLimit(aMiterLimit)
  97. , mDashPattern(aDashLength > 0 ? aDashPattern : 0)
  98. , mDashLength(aDashLength)
  99. , mDashOffset(aDashOffset)
  100. , mLineJoin(aLineJoin)
  101. , mLineCap(aLineCap)
  102. {
  103. MOZ_ASSERT(aDashLength == 0 || aDashPattern);
  104. }
  105. Float mLineWidth; //!< Width of the stroke in userspace.
  106. Float mMiterLimit; //!< Miter limit in units of linewidth
  107. const Float* mDashPattern; /**< Series of on/off userspace lengths defining dash.
  108. Owned by the caller; must live at least as long as
  109. this StrokeOptions.
  110. mDashPattern != null <=> mDashLength > 0. */
  111. size_t mDashLength; //!< Number of on/off lengths in mDashPattern.
  112. Float mDashOffset; /**< Userspace offset within mDashPattern at which
  113. stroking begins. */
  114. JoinStyle mLineJoin; //!< Join style used for joining lines.
  115. CapStyle mLineCap; //!< Cap style used for capping lines.
  116. };
  117. /**
  118. * This structure supplies additional options for calls to DrawSurface.
  119. */
  120. struct DrawSurfaceOptions {
  121. /// For constructor parameter description, see member data documentation.
  122. explicit DrawSurfaceOptions(SamplingFilter aSamplingFilter = SamplingFilter::LINEAR,
  123. SamplingBounds aSamplingBounds = SamplingBounds::UNBOUNDED)
  124. : mSamplingFilter(aSamplingFilter)
  125. , mSamplingBounds(aSamplingBounds)
  126. { }
  127. SamplingFilter mSamplingFilter; /**< SamplingFilter used when resampling source surface
  128. region to the destination region. */
  129. SamplingBounds mSamplingBounds; /**< This indicates whether the implementation is
  130. allowed to sample pixels outside the source
  131. rectangle as specified in DrawSurface on
  132. the surface. */
  133. };
  134. /**
  135. * This class is used to store gradient stops, it can only be used with a
  136. * matching DrawTarget. Not adhering to this condition will make a draw call
  137. * fail.
  138. */
  139. class GradientStops : public RefCounted<GradientStops>
  140. {
  141. public:
  142. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(GradientStops)
  143. virtual ~GradientStops() {}
  144. virtual BackendType GetBackendType() const = 0;
  145. virtual bool IsValid() const { return true; }
  146. protected:
  147. GradientStops() {}
  148. };
  149. /**
  150. * This is the base class for 'patterns'. Patterns describe the pixels used as
  151. * the source for a masked composition operation that is done by the different
  152. * drawing commands. These objects are not backend specific, however for
  153. * example the gradient stops on a gradient pattern can be backend specific.
  154. */
  155. class Pattern
  156. {
  157. public:
  158. virtual ~Pattern() {}
  159. virtual PatternType GetType() const = 0;
  160. protected:
  161. Pattern() {}
  162. };
  163. class ColorPattern : public Pattern
  164. {
  165. public:
  166. // Explicit because consumers should generally use ToDeviceColor when
  167. // creating a ColorPattern.
  168. explicit ColorPattern(const Color &aColor)
  169. : mColor(aColor)
  170. {}
  171. virtual PatternType GetType() const override
  172. {
  173. return PatternType::COLOR;
  174. }
  175. Color mColor;
  176. };
  177. /**
  178. * This class is used for Linear Gradient Patterns, the gradient stops are
  179. * stored in a separate object and are backend dependent. This class itself
  180. * may be used on the stack.
  181. */
  182. class LinearGradientPattern : public Pattern
  183. {
  184. public:
  185. /// For constructor parameter description, see member data documentation.
  186. LinearGradientPattern(const Point &aBegin,
  187. const Point &aEnd,
  188. GradientStops *aStops,
  189. const Matrix &aMatrix = Matrix())
  190. : mBegin(aBegin)
  191. , mEnd(aEnd)
  192. , mStops(aStops)
  193. , mMatrix(aMatrix)
  194. {
  195. }
  196. virtual PatternType GetType() const override
  197. {
  198. return PatternType::LINEAR_GRADIENT;
  199. }
  200. Point mBegin; //!< Start of the linear gradient
  201. Point mEnd; /**< End of the linear gradient - NOTE: In the case
  202. of a zero length gradient it will act as the
  203. color of the last stop. */
  204. RefPtr<GradientStops> mStops; /**< GradientStops object for this gradient, this
  205. should match the backend type of the draw
  206. target this pattern will be used with. */
  207. Matrix mMatrix; /**< A matrix that transforms the pattern into
  208. user space */
  209. };
  210. /**
  211. * This class is used for Radial Gradient Patterns, the gradient stops are
  212. * stored in a separate object and are backend dependent. This class itself
  213. * may be used on the stack.
  214. */
  215. class RadialGradientPattern : public Pattern
  216. {
  217. public:
  218. /// For constructor parameter description, see member data documentation.
  219. RadialGradientPattern(const Point &aCenter1,
  220. const Point &aCenter2,
  221. Float aRadius1,
  222. Float aRadius2,
  223. GradientStops *aStops,
  224. const Matrix &aMatrix = Matrix())
  225. : mCenter1(aCenter1)
  226. , mCenter2(aCenter2)
  227. , mRadius1(aRadius1)
  228. , mRadius2(aRadius2)
  229. , mStops(aStops)
  230. , mMatrix(aMatrix)
  231. {
  232. }
  233. virtual PatternType GetType() const override
  234. {
  235. return PatternType::RADIAL_GRADIENT;
  236. }
  237. Point mCenter1; //!< Center of the inner (focal) circle.
  238. Point mCenter2; //!< Center of the outer circle.
  239. Float mRadius1; //!< Radius of the inner (focal) circle.
  240. Float mRadius2; //!< Radius of the outer circle.
  241. RefPtr<GradientStops> mStops; /**< GradientStops object for this gradient, this
  242. should match the backend type of the draw target
  243. this pattern will be used with. */
  244. Matrix mMatrix; //!< A matrix that transforms the pattern into user space
  245. };
  246. /**
  247. * This class is used for Surface Patterns, they wrap a surface and a
  248. * repetition mode for the surface. This may be used on the stack.
  249. */
  250. class SurfacePattern : public Pattern
  251. {
  252. public:
  253. /// For constructor parameter description, see member data documentation.
  254. SurfacePattern(SourceSurface *aSourceSurface, ExtendMode aExtendMode,
  255. const Matrix &aMatrix = Matrix(),
  256. SamplingFilter aSamplingFilter = SamplingFilter::GOOD,
  257. const IntRect &aSamplingRect = IntRect())
  258. : mSurface(aSourceSurface)
  259. , mExtendMode(aExtendMode)
  260. , mSamplingFilter(aSamplingFilter)
  261. , mMatrix(aMatrix)
  262. , mSamplingRect(aSamplingRect)
  263. {}
  264. virtual PatternType GetType() const override
  265. {
  266. return PatternType::SURFACE;
  267. }
  268. RefPtr<SourceSurface> mSurface; //!< Surface to use for drawing
  269. ExtendMode mExtendMode; /**< This determines how the image is extended
  270. outside the bounds of the image */
  271. SamplingFilter mSamplingFilter; //!< Resampling filter for resampling the image.
  272. Matrix mMatrix; //!< Transforms the pattern into user space
  273. IntRect mSamplingRect; /**< Rect that must not be sampled outside of,
  274. or an empty rect if none has been specified. */
  275. };
  276. class StoredPattern;
  277. class DrawTargetCaptureImpl;
  278. /**
  279. * This is the base class for source surfaces. These objects are surfaces
  280. * which may be used as a source in a SurfacePattern or a DrawSurface call.
  281. * They cannot be drawn to directly.
  282. *
  283. * Although SourceSurface has thread-safe refcount, some SourceSurface cannot
  284. * be used on random threads at the same time. Only DataSourceSurface can be
  285. * used on random threads now. This will be fixed in the future. Eventually
  286. * all SourceSurface should be thread-safe.
  287. */
  288. class SourceSurface : public external::AtomicRefCounted<SourceSurface>
  289. {
  290. public:
  291. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(SourceSurface)
  292. virtual ~SourceSurface() {}
  293. virtual SurfaceType GetType() const = 0;
  294. virtual IntSize GetSize() const = 0;
  295. virtual SurfaceFormat GetFormat() const = 0;
  296. /** This returns false if some event has made this source surface invalid for
  297. * usage with current DrawTargets. For example in the case of Direct2D this
  298. * could return false if we have switched devices since this surface was
  299. * created.
  300. */
  301. virtual bool IsValid() const { return true; }
  302. /**
  303. * This function will get a DataSourceSurface for this surface, a
  304. * DataSourceSurface's data can be accessed directly.
  305. */
  306. virtual already_AddRefed<DataSourceSurface> GetDataSurface() = 0;
  307. /** Tries to get this SourceSurface's native surface. This will fail if aType
  308. * is not the type of this SourceSurface's native surface.
  309. */
  310. virtual void *GetNativeSurface(NativeSurfaceType aType) {
  311. return nullptr;
  312. }
  313. void AddUserData(UserDataKey *key, void *userData, void (*destroy)(void*)) {
  314. mUserData.Add(key, userData, destroy);
  315. }
  316. void *GetUserData(UserDataKey *key) {
  317. return mUserData.Get(key);
  318. }
  319. protected:
  320. friend class DrawTargetCaptureImpl;
  321. friend class StoredPattern;
  322. // This is for internal use, it ensures the SourceSurface's data remains
  323. // valid during the lifetime of the SourceSurface.
  324. // @todo XXX - We need something better here :(. But we may be able to get rid
  325. // of CreateWrappingDataSourceSurface in the future.
  326. virtual void GuaranteePersistance() {}
  327. UserData mUserData;
  328. };
  329. class DataSourceSurface : public SourceSurface
  330. {
  331. public:
  332. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(DataSourceSurface, override)
  333. DataSourceSurface()
  334. : mIsMapped(false)
  335. {
  336. }
  337. #ifdef DEBUG
  338. virtual ~DataSourceSurface()
  339. {
  340. MOZ_ASSERT(!mIsMapped, "Someone forgot to call Unmap()");
  341. }
  342. #endif
  343. struct MappedSurface {
  344. uint8_t *mData;
  345. int32_t mStride;
  346. };
  347. enum MapType {
  348. READ,
  349. WRITE,
  350. READ_WRITE
  351. };
  352. /**
  353. * This is a scoped version of Map(). Map() is called in the constructor and
  354. * Unmap() in the destructor. Use this for automatic unmapping of your data
  355. * surfaces.
  356. *
  357. * Use IsMapped() to verify whether Map() succeeded or not.
  358. */
  359. class ScopedMap {
  360. public:
  361. explicit ScopedMap(DataSourceSurface* aSurface, MapType aType)
  362. : mSurface(aSurface)
  363. , mIsMapped(aSurface->Map(aType, &mMap)) {}
  364. virtual ~ScopedMap()
  365. {
  366. if (mIsMapped) {
  367. mSurface->Unmap();
  368. }
  369. }
  370. uint8_t* GetData() const
  371. {
  372. MOZ_ASSERT(mIsMapped);
  373. return mMap.mData;
  374. }
  375. int32_t GetStride() const
  376. {
  377. MOZ_ASSERT(mIsMapped);
  378. return mMap.mStride;
  379. }
  380. const MappedSurface* GetMappedSurface() const
  381. {
  382. MOZ_ASSERT(mIsMapped);
  383. return &mMap;
  384. }
  385. bool IsMapped() const { return mIsMapped; }
  386. private:
  387. RefPtr<DataSourceSurface> mSurface;
  388. MappedSurface mMap;
  389. bool mIsMapped;
  390. };
  391. virtual SurfaceType GetType() const override { return SurfaceType::DATA; }
  392. /** @deprecated
  393. * Get the raw bitmap data of the surface.
  394. * Can return null if there was OOM allocating surface data.
  395. */
  396. virtual uint8_t *GetData() = 0;
  397. /** @deprecated
  398. * Stride of the surface, distance in bytes between the start of the image
  399. * data belonging to row y and row y+1. This may be negative.
  400. * Can return 0 if there was OOM allocating surface data.
  401. */
  402. virtual int32_t Stride() = 0;
  403. /**
  404. * The caller is responsible for ensuring aMappedSurface is not null.
  405. */
  406. virtual bool Map(MapType, MappedSurface *aMappedSurface)
  407. {
  408. aMappedSurface->mData = GetData();
  409. aMappedSurface->mStride = Stride();
  410. mIsMapped = !!aMappedSurface->mData;
  411. return mIsMapped;
  412. }
  413. virtual void Unmap()
  414. {
  415. MOZ_ASSERT(mIsMapped);
  416. mIsMapped = false;
  417. }
  418. /**
  419. * Returns a DataSourceSurface with the same data as this one, but
  420. * guaranteed to have surface->GetType() == SurfaceType::DATA.
  421. *
  422. * The returning surface might be null, because of OOM or gfx device reset.
  423. * The caller needs to do null-check before using it.
  424. */
  425. virtual already_AddRefed<DataSourceSurface> GetDataSurface() override;
  426. protected:
  427. bool mIsMapped;
  428. };
  429. /** This is an abstract object that accepts path segments. */
  430. class PathSink : public RefCounted<PathSink>
  431. {
  432. public:
  433. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(PathSink)
  434. virtual ~PathSink() {}
  435. /** Move the current point in the path, any figure currently being drawn will
  436. * be considered closed during fill operations, however when stroking the
  437. * closing line segment will not be drawn.
  438. */
  439. virtual void MoveTo(const Point &aPoint) = 0;
  440. /** Add a linesegment to the current figure */
  441. virtual void LineTo(const Point &aPoint) = 0;
  442. /** Add a cubic bezier curve to the current figure */
  443. virtual void BezierTo(const Point &aCP1,
  444. const Point &aCP2,
  445. const Point &aCP3) = 0;
  446. /** Add a quadratic bezier curve to the current figure */
  447. virtual void QuadraticBezierTo(const Point &aCP1,
  448. const Point &aCP2) = 0;
  449. /** Close the current figure, this will essentially generate a line segment
  450. * from the current point to the starting point for the current figure
  451. */
  452. virtual void Close() = 0;
  453. /** Add an arc to the current figure */
  454. virtual void Arc(const Point &aOrigin, float aRadius, float aStartAngle,
  455. float aEndAngle, bool aAntiClockwise = false) = 0;
  456. /** Point the current subpath is at - or where the next subpath will start
  457. * if there is no active subpath.
  458. */
  459. virtual Point CurrentPoint() const = 0;
  460. };
  461. class PathBuilder;
  462. class FlattenedPath;
  463. /** The path class is used to create (sets of) figures of any shape that can be
  464. * filled or stroked to a DrawTarget
  465. */
  466. class Path : public RefCounted<Path>
  467. {
  468. public:
  469. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(Path)
  470. virtual ~Path();
  471. virtual BackendType GetBackendType() const = 0;
  472. /** This returns a PathBuilder object that contains a copy of the contents of
  473. * this path and is still writable.
  474. */
  475. inline already_AddRefed<PathBuilder> CopyToBuilder() const {
  476. return CopyToBuilder(GetFillRule());
  477. }
  478. inline already_AddRefed<PathBuilder> TransformedCopyToBuilder(const Matrix &aTransform) const {
  479. return TransformedCopyToBuilder(aTransform, GetFillRule());
  480. }
  481. /** This returns a PathBuilder object that contains a copy of the contents of
  482. * this path, converted to use the specified FillRule, and still writable.
  483. */
  484. virtual already_AddRefed<PathBuilder> CopyToBuilder(FillRule aFillRule) const = 0;
  485. virtual already_AddRefed<PathBuilder> TransformedCopyToBuilder(const Matrix &aTransform,
  486. FillRule aFillRule) const = 0;
  487. /** This function checks if a point lies within a path. It allows passing a
  488. * transform that will transform the path to the coordinate space in which
  489. * aPoint is given.
  490. */
  491. virtual bool ContainsPoint(const Point &aPoint, const Matrix &aTransform) const = 0;
  492. /** This function checks if a point lies within the stroke of a path using the
  493. * specified strokeoptions. It allows passing a transform that will transform
  494. * the path to the coordinate space in which aPoint is given.
  495. */
  496. virtual bool StrokeContainsPoint(const StrokeOptions &aStrokeOptions,
  497. const Point &aPoint,
  498. const Matrix &aTransform) const = 0;
  499. /** This functions gets the bounds of this path. These bounds are not
  500. * guaranteed to be tight. A transform may be specified that gives the bounds
  501. * after application of the transform.
  502. */
  503. virtual Rect GetBounds(const Matrix &aTransform = Matrix()) const = 0;
  504. /** This function gets the bounds of the stroke of this path using the
  505. * specified strokeoptions. These bounds are not guaranteed to be tight.
  506. * A transform may be specified that gives the bounds after application of
  507. * the transform.
  508. */
  509. virtual Rect GetStrokedBounds(const StrokeOptions &aStrokeOptions,
  510. const Matrix &aTransform = Matrix()) const = 0;
  511. /** Take the contents of this path and stream it to another sink, this works
  512. * regardless of the backend that might be used for the destination sink.
  513. */
  514. virtual void StreamToSink(PathSink *aSink) const = 0;
  515. /** This gets the fillrule this path's builder was created with. This is not
  516. * mutable.
  517. */
  518. virtual FillRule GetFillRule() const = 0;
  519. virtual Float ComputeLength();
  520. virtual Point ComputePointAtLength(Float aLength,
  521. Point* aTangent = nullptr);
  522. protected:
  523. Path();
  524. void EnsureFlattenedPath();
  525. RefPtr<FlattenedPath> mFlattenedPath;
  526. };
  527. /** The PathBuilder class allows path creation. Once finish is called on the
  528. * pathbuilder it may no longer be written to.
  529. */
  530. class PathBuilder : public PathSink
  531. {
  532. public:
  533. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(PathBuilder)
  534. /** Finish writing to the path and return a Path object that can be used for
  535. * drawing. Future use of the builder results in a crash!
  536. */
  537. virtual already_AddRefed<Path> Finish() = 0;
  538. virtual BackendType GetBackendType() const = 0;
  539. };
  540. struct Glyph
  541. {
  542. uint32_t mIndex;
  543. Point mPosition;
  544. };
  545. /** This class functions as a glyph buffer that can be drawn to a DrawTarget.
  546. * @todo XXX - This should probably contain the guts of gfxTextRun in the future as
  547. * roc suggested. But for now it's a simple container for a glyph vector.
  548. */
  549. struct GlyphBuffer
  550. {
  551. const Glyph *mGlyphs; //!< A pointer to a buffer of glyphs. Managed by the caller.
  552. uint32_t mNumGlyphs; //!< Number of glyphs mGlyphs points to.
  553. };
  554. struct GlyphMetrics
  555. {
  556. // Horizontal distance from the origin to the leftmost side of the bounding
  557. // box of the drawn glyph. This can be negative!
  558. Float mXBearing;
  559. // Horizontal distance from the origin of this glyph to the origin of the
  560. // next glyph.
  561. Float mXAdvance;
  562. // Vertical distance from the origin to the topmost side of the bounding box
  563. // of the drawn glyph.
  564. Float mYBearing;
  565. // Vertical distance from the origin of this glyph to the origin of the next
  566. // glyph, this is used when drawing vertically and will typically be 0.
  567. Float mYAdvance;
  568. // Width of the glyph's black box.
  569. Float mWidth;
  570. // Height of the glyph's black box.
  571. Float mHeight;
  572. };
  573. /** This class is an abstraction of a backend/platform specific font object
  574. * at a particular size. It is passed into text drawing calls to describe
  575. * the font used for the drawing call.
  576. */
  577. class ScaledFont : public RefCounted<ScaledFont>
  578. {
  579. public:
  580. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(ScaledFont)
  581. virtual ~ScaledFont() {}
  582. typedef void (*FontFileDataOutput)(const uint8_t *aData, uint32_t aLength, uint32_t aIndex, Float aGlyphSize, void *aBaton);
  583. typedef void (*FontInstanceDataOutput)(const uint8_t* aData, uint32_t aLength, void* aBaton);
  584. typedef void (*FontDescriptorOutput)(const uint8_t *aData, uint32_t aLength, Float aFontSize, void *aBaton);
  585. virtual FontType GetType() const = 0;
  586. virtual AntialiasMode GetDefaultAAMode() {
  587. if (gfxPrefs::DisableAllTextAA()) {
  588. return AntialiasMode::NONE;
  589. }
  590. return AntialiasMode::DEFAULT;
  591. }
  592. /** This allows getting a path that describes the outline of a set of glyphs.
  593. * A target is passed in so that the guarantee is made the returned path
  594. * can be used with any DrawTarget that has the same backend as the one
  595. * passed in.
  596. */
  597. virtual already_AddRefed<Path> GetPathForGlyphs(const GlyphBuffer &aBuffer, const DrawTarget *aTarget) = 0;
  598. /** This copies the path describing the glyphs into a PathBuilder. We use this
  599. * API rather than a generic API to append paths because it allows easier
  600. * implementation in some backends, and more efficient implementation in
  601. * others.
  602. */
  603. virtual void CopyGlyphsToBuilder(const GlyphBuffer &aBuffer, PathBuilder *aBuilder, const Matrix *aTransformHint = nullptr) = 0;
  604. /* This gets the metrics of a set of glyphs for the current font face.
  605. */
  606. virtual void GetGlyphDesignMetrics(const uint16_t* aGlyphIndices, uint32_t aNumGlyphs, GlyphMetrics* aGlyphMetrics) = 0;
  607. virtual bool GetFontFileData(FontFileDataOutput, void *) { return false; }
  608. virtual bool GetFontInstanceData(FontInstanceDataOutput, void *) { return false; }
  609. virtual bool GetFontDescriptor(FontDescriptorOutput, void *) { return false; }
  610. void AddUserData(UserDataKey *key, void *userData, void (*destroy)(void*)) {
  611. mUserData.Add(key, userData, destroy);
  612. }
  613. void *GetUserData(UserDataKey *key) {
  614. return mUserData.Get(key);
  615. }
  616. protected:
  617. ScaledFont() {}
  618. UserData mUserData;
  619. };
  620. /**
  621. * Derived classes hold a native font resource from which to create
  622. * ScaledFonts.
  623. */
  624. class NativeFontResource : public RefCounted<NativeFontResource>
  625. {
  626. public:
  627. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(NativeFontResource)
  628. /**
  629. * Creates a ScaledFont using the font corresponding to the index and
  630. * the given glyph size.
  631. *
  632. * @param aIndex index for the font within the resource.
  633. * @param aGlyphSize the size of ScaledFont required.
  634. * @param aInstanceData pointer to read-only buffer of any available instance data.
  635. * @param aInstanceDataLength the size of the instance data.
  636. * @return an already_addrefed ScaledFont, containing nullptr if failed.
  637. */
  638. virtual already_AddRefed<ScaledFont>
  639. CreateScaledFont(uint32_t aIndex, Float aGlyphSize,
  640. const uint8_t* aInstanceData, uint32_t aInstanceDataLength) = 0;
  641. virtual ~NativeFontResource() {};
  642. };
  643. /** This class is designed to allow passing additional glyph rendering
  644. * parameters to the glyph drawing functions. This is an empty wrapper class
  645. * merely used to allow holding on to and passing around platform specific
  646. * parameters. This is because different platforms have unique rendering
  647. * parameters.
  648. */
  649. class GlyphRenderingOptions : public RefCounted<GlyphRenderingOptions>
  650. {
  651. public:
  652. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(GlyphRenderingOptions)
  653. virtual ~GlyphRenderingOptions() {}
  654. virtual FontType GetType() const = 0;
  655. protected:
  656. GlyphRenderingOptions() {}
  657. };
  658. class DrawTargetCapture;
  659. /** This is the main class used for all the drawing. It is created through the
  660. * factory and accepts drawing commands. The results of drawing to a target
  661. * may be used either through a Snapshot or by flushing the target and directly
  662. * accessing the backing store a DrawTarget was created with.
  663. */
  664. class DrawTarget : public RefCounted<DrawTarget>
  665. {
  666. public:
  667. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(DrawTarget)
  668. DrawTarget() : mTransformDirty(false), mPermitSubpixelAA(false) {}
  669. virtual ~DrawTarget() {}
  670. virtual bool IsValid() const { return true; };
  671. virtual DrawTargetType GetType() const = 0;
  672. virtual BackendType GetBackendType() const = 0;
  673. virtual bool IsRecording() const { return false; }
  674. /**
  675. * Returns a SourceSurface which is a snapshot of the current contents of the DrawTarget.
  676. * Multiple calls to Snapshot() without any drawing operations in between will
  677. * normally return the same SourceSurface object.
  678. */
  679. virtual already_AddRefed<SourceSurface> Snapshot() = 0;
  680. virtual IntSize GetSize() = 0;
  681. /**
  682. * If possible returns the bits to this DrawTarget for direct manipulation. While
  683. * the bits is locked any modifications to this DrawTarget is forbidden.
  684. * Release takes the original data pointer for safety.
  685. */
  686. virtual bool LockBits(uint8_t** aData, IntSize* aSize,
  687. int32_t* aStride, SurfaceFormat* aFormat,
  688. IntPoint* aOrigin = nullptr) { return false; }
  689. virtual void ReleaseBits(uint8_t* aData) {}
  690. /** Ensure that the DrawTarget backend has flushed all drawing operations to
  691. * this draw target. This must be called before using the backing surface of
  692. * this draw target outside of GFX 2D code.
  693. */
  694. virtual void Flush() = 0;
  695. /**
  696. * Realize a DrawTargetCapture onto the draw target.
  697. *
  698. * @param aSource Capture DrawTarget to draw
  699. * @param aTransform Transform to apply when replaying commands
  700. */
  701. virtual void DrawCapturedDT(DrawTargetCapture *aCaptureDT,
  702. const Matrix& aTransform);
  703. /**
  704. * Draw a surface to the draw target. Possibly doing partial drawing or
  705. * applying scaling. No sampling happens outside the source.
  706. *
  707. * @param aSurface Source surface to draw
  708. * @param aDest Destination rectangle that this drawing operation should draw to
  709. * @param aSource Source rectangle in aSurface coordinates, this area of aSurface
  710. * will be stretched to the size of aDest.
  711. * @param aOptions General draw options that are applied to the operation
  712. * @param aSurfOptions DrawSurface options that are applied
  713. */
  714. virtual void DrawSurface(SourceSurface *aSurface,
  715. const Rect &aDest,
  716. const Rect &aSource,
  717. const DrawSurfaceOptions &aSurfOptions = DrawSurfaceOptions(),
  718. const DrawOptions &aOptions = DrawOptions()) = 0;
  719. /**
  720. * Draw the output of a FilterNode to the DrawTarget.
  721. *
  722. * @param aNode FilterNode to draw
  723. * @param aSourceRect Source rectangle in FilterNode space to draw
  724. * @param aDestPoint Destination point on the DrawTarget to draw the
  725. * SourceRectangle of the filter output to
  726. */
  727. virtual void DrawFilter(FilterNode *aNode,
  728. const Rect &aSourceRect,
  729. const Point &aDestPoint,
  730. const DrawOptions &aOptions = DrawOptions()) = 0;
  731. /**
  732. * Blend a surface to the draw target with a shadow. The shadow is drawn as a
  733. * gaussian blur using a specified sigma. The shadow is clipped to the size
  734. * of the input surface, so the input surface should contain a transparent
  735. * border the size of the approximate coverage of the blur (3 * aSigma).
  736. * NOTE: This function works in device space!
  737. *
  738. * @param aSurface Source surface to draw.
  739. * @param aDest Destination point that this drawing operation should draw to.
  740. * @param aColor Color of the drawn shadow
  741. * @param aOffset Offset of the shadow
  742. * @param aSigma Sigma used for the guassian filter kernel
  743. * @param aOperator Composition operator used
  744. */
  745. virtual void DrawSurfaceWithShadow(SourceSurface *aSurface,
  746. const Point &aDest,
  747. const Color &aColor,
  748. const Point &aOffset,
  749. Float aSigma,
  750. CompositionOp aOperator) = 0;
  751. /**
  752. * Clear a rectangle on the draw target to transparent black. This will
  753. * respect the clipping region and transform.
  754. *
  755. * @param aRect Rectangle to clear
  756. */
  757. virtual void ClearRect(const Rect &aRect) = 0;
  758. /**
  759. * This is essentially a 'memcpy' between two surfaces. It moves a pixel
  760. * aligned area from the source surface unscaled directly onto the
  761. * drawtarget. This ignores both transform and clip.
  762. *
  763. * @param aSurface Surface to copy from
  764. * @param aSourceRect Source rectangle to be copied
  765. * @param aDest Destination point to copy the surface to
  766. */
  767. virtual void CopySurface(SourceSurface *aSurface,
  768. const IntRect &aSourceRect,
  769. const IntPoint &aDestination) = 0;
  770. /** @see CopySurface
  771. * Same as CopySurface, except uses itself as the source.
  772. *
  773. * Some backends may be able to optimize this better
  774. * than just taking a snapshot and using CopySurface.
  775. */
  776. virtual void CopyRect(const IntRect &aSourceRect,
  777. const IntPoint &aDestination)
  778. {
  779. RefPtr<SourceSurface> source = Snapshot();
  780. CopySurface(source, aSourceRect, aDestination);
  781. }
  782. /**
  783. * Fill a rectangle on the DrawTarget with a certain source pattern.
  784. *
  785. * @param aRect Rectangle that forms the mask of this filling operation
  786. * @param aPattern Pattern that forms the source of this filling operation
  787. * @param aOptions Options that are applied to this operation
  788. */
  789. virtual void FillRect(const Rect &aRect,
  790. const Pattern &aPattern,
  791. const DrawOptions &aOptions = DrawOptions()) = 0;
  792. /**
  793. * Stroke a rectangle on the DrawTarget with a certain source pattern.
  794. *
  795. * @param aRect Rectangle that forms the mask of this stroking operation
  796. * @param aPattern Pattern that forms the source of this stroking operation
  797. * @param aOptions Options that are applied to this operation
  798. */
  799. virtual void StrokeRect(const Rect &aRect,
  800. const Pattern &aPattern,
  801. const StrokeOptions &aStrokeOptions = StrokeOptions(),
  802. const DrawOptions &aOptions = DrawOptions()) = 0;
  803. /**
  804. * Stroke a line on the DrawTarget with a certain source pattern.
  805. *
  806. * @param aStart Starting point of the line
  807. * @param aEnd End point of the line
  808. * @param aPattern Pattern that forms the source of this stroking operation
  809. * @param aOptions Options that are applied to this operation
  810. */
  811. virtual void StrokeLine(const Point &aStart,
  812. const Point &aEnd,
  813. const Pattern &aPattern,
  814. const StrokeOptions &aStrokeOptions = StrokeOptions(),
  815. const DrawOptions &aOptions = DrawOptions()) = 0;
  816. /**
  817. * Stroke a path on the draw target with a certain source pattern.
  818. *
  819. * @param aPath Path that is to be stroked
  820. * @param aPattern Pattern that should be used for the stroke
  821. * @param aStrokeOptions Stroke options used for this operation
  822. * @param aOptions Draw options used for this operation
  823. */
  824. virtual void Stroke(const Path *aPath,
  825. const Pattern &aPattern,
  826. const StrokeOptions &aStrokeOptions = StrokeOptions(),
  827. const DrawOptions &aOptions = DrawOptions()) = 0;
  828. /**
  829. * Fill a path on the draw target with a certain source pattern.
  830. *
  831. * @param aPath Path that is to be filled
  832. * @param aPattern Pattern that should be used for the fill
  833. * @param aOptions Draw options used for this operation
  834. */
  835. virtual void Fill(const Path *aPath,
  836. const Pattern &aPattern,
  837. const DrawOptions &aOptions = DrawOptions()) = 0;
  838. /**
  839. * Fill a series of clyphs on the draw target with a certain source pattern.
  840. */
  841. virtual void FillGlyphs(ScaledFont *aFont,
  842. const GlyphBuffer &aBuffer,
  843. const Pattern &aPattern,
  844. const DrawOptions &aOptions = DrawOptions(),
  845. const GlyphRenderingOptions *aRenderingOptions = nullptr) = 0;
  846. /**
  847. * This takes a source pattern and a mask, and composites the source pattern
  848. * onto the destination surface using the alpha channel of the mask pattern
  849. * as a mask for the operation.
  850. *
  851. * @param aSource Source pattern
  852. * @param aMask Mask pattern
  853. * @param aOptions Drawing options
  854. */
  855. virtual void Mask(const Pattern &aSource,
  856. const Pattern &aMask,
  857. const DrawOptions &aOptions = DrawOptions()) = 0;
  858. /**
  859. * This takes a source pattern and a mask, and composites the source pattern
  860. * onto the destination surface using the alpha channel of the mask source.
  861. * The operation is bound by the extents of the mask.
  862. *
  863. * @param aSource Source pattern
  864. * @param aMask Mask surface
  865. * @param aOffset a transformed offset that the surface is masked at
  866. * @param aOptions Drawing options
  867. */
  868. virtual void MaskSurface(const Pattern &aSource,
  869. SourceSurface *aMask,
  870. Point aOffset,
  871. const DrawOptions &aOptions = DrawOptions()) = 0;
  872. /**
  873. * Draw aSurface using the 3D transform aMatrix. The DrawTarget's transform
  874. * and clip are applied after the 3D transform.
  875. *
  876. * If the transform fails (i.e. because aMatrix is singular), false is returned and nothing is drawn.
  877. */
  878. virtual bool Draw3DTransformedSurface(SourceSurface* aSurface,
  879. const Matrix4x4& aMatrix);
  880. /**
  881. * Push a clip to the DrawTarget.
  882. *
  883. * @param aPath The path to clip to
  884. */
  885. virtual void PushClip(const Path *aPath) = 0;
  886. /**
  887. * Push an axis-aligned rectangular clip to the DrawTarget. This rectangle
  888. * is specified in user space.
  889. *
  890. * @param aRect The rect to clip to
  891. */
  892. virtual void PushClipRect(const Rect &aRect) = 0;
  893. /**
  894. * Push a clip region specifed by the union of axis-aligned rectangular
  895. * clips to the DrawTarget. These rectangles are specified in device space.
  896. * This must be balanced by a corresponding call to PopClip within a layer.
  897. *
  898. * @param aRects The rects to clip to
  899. * @param aCount The number of rectangles
  900. */
  901. virtual void PushDeviceSpaceClipRects(const IntRect* aRects, uint32_t aCount);
  902. /** Pop a clip from the DrawTarget. A pop without a corresponding push will
  903. * be ignored.
  904. */
  905. virtual void PopClip() = 0;
  906. /**
  907. * Push a 'layer' to the DrawTarget, a layer is a temporary surface that all
  908. * drawing will be redirected to, this is used for example to support group
  909. * opacity or the masking of groups. Clips must be balanced within a layer,
  910. * i.e. between a matching PushLayer/PopLayer pair there must be as many
  911. * PushClip(Rect) calls as there are PopClip calls.
  912. *
  913. * @param aOpaque Whether the layer will be opaque
  914. * @param aOpacity Opacity of the layer
  915. * @param aMask Mask applied to the layer
  916. * @param aMaskTransform Transform applied to the layer mask
  917. * @param aBounds Optional bounds in device space to which the layer is
  918. * limited in size.
  919. * @param aCopyBackground Whether to copy the background into the layer, this
  920. * is only supported when aOpaque is true.
  921. */
  922. virtual void PushLayer(bool aOpaque, Float aOpacity,
  923. SourceSurface* aMask,
  924. const Matrix& aMaskTransform,
  925. const IntRect& aBounds = IntRect(),
  926. bool aCopyBackground = false) { MOZ_CRASH("GFX: PushLayer"); }
  927. /**
  928. * This balances a call to PushLayer and proceeds to blend the layer back
  929. * onto the background. This blend will blend the temporary surface back
  930. * onto the target in device space using POINT sampling and operator over.
  931. */
  932. virtual void PopLayer() { MOZ_CRASH("GFX: PopLayer"); }
  933. /**
  934. * Create a SourceSurface optimized for use with this DrawTarget from
  935. * existing bitmap data in memory.
  936. *
  937. * The SourceSurface does not take ownership of aData, and may be freed at any time.
  938. */
  939. virtual already_AddRefed<SourceSurface> CreateSourceSurfaceFromData(unsigned char *aData,
  940. const IntSize &aSize,
  941. int32_t aStride,
  942. SurfaceFormat aFormat) const = 0;
  943. /**
  944. * Create a SourceSurface optimized for use with this DrawTarget from an
  945. * arbitrary SourceSurface type supported by this backend. This may return
  946. * aSourceSurface or some other existing surface.
  947. */
  948. virtual already_AddRefed<SourceSurface> OptimizeSourceSurface(SourceSurface *aSurface) const = 0;
  949. virtual already_AddRefed<SourceSurface> OptimizeSourceSurfaceForUnknownAlpha(SourceSurface *aSurface) const {
  950. return OptimizeSourceSurface(aSurface);
  951. }
  952. /**
  953. * Create a SourceSurface for a type of NativeSurface. This may fail if the
  954. * draw target does not know how to deal with the type of NativeSurface passed
  955. * in. If this succeeds, the SourceSurface takes the ownersip of the NativeSurface.
  956. */
  957. virtual already_AddRefed<SourceSurface>
  958. CreateSourceSurfaceFromNativeSurface(const NativeSurface &aSurface) const = 0;
  959. /**
  960. * Create a DrawTarget whose snapshot is optimized for use with this DrawTarget.
  961. */
  962. virtual already_AddRefed<DrawTarget>
  963. CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const = 0;
  964. /**
  965. * Create a DrawTarget that captures the drawing commands and can be replayed
  966. * onto a compatible DrawTarget afterwards.
  967. *
  968. * @param aSize Size of the area this DT will capture.
  969. */
  970. virtual already_AddRefed<DrawTargetCapture> CreateCaptureDT(const IntSize& aSize);
  971. /**
  972. * Create a draw target optimized for drawing a shadow.
  973. *
  974. * Note that aSigma is the blur radius that must be used when we draw the
  975. * shadow. Also note that this doesn't affect the size of the allocated
  976. * surface, the caller is still responsible for including the shadow area in
  977. * its size.
  978. */
  979. virtual already_AddRefed<DrawTarget>
  980. CreateShadowDrawTarget(const IntSize &aSize, SurfaceFormat aFormat,
  981. float aSigma) const
  982. {
  983. return CreateSimilarDrawTarget(aSize, aFormat);
  984. }
  985. /**
  986. * Create a path builder with the specified fillmode.
  987. *
  988. * We need the fill mode up front because of Direct2D.
  989. * ID2D1SimplifiedGeometrySink requires the fill mode
  990. * to be set before calling BeginFigure().
  991. */
  992. virtual already_AddRefed<PathBuilder> CreatePathBuilder(FillRule aFillRule = FillRule::FILL_WINDING) const = 0;
  993. /**
  994. * Create a GradientStops object that holds information about a set of
  995. * gradient stops, this object is required for linear or radial gradient
  996. * patterns to represent the color stops in the gradient.
  997. *
  998. * @param aStops An array of gradient stops
  999. * @param aNumStops Number of stops in the array aStops
  1000. * @param aExtendNone This describes how to extend the stop color outside of the
  1001. * gradient area.
  1002. */
  1003. virtual already_AddRefed<GradientStops>
  1004. CreateGradientStops(GradientStop *aStops,
  1005. uint32_t aNumStops,
  1006. ExtendMode aExtendMode = ExtendMode::CLAMP) const = 0;
  1007. /**
  1008. * Create a FilterNode object that can be used to apply a filter to various
  1009. * inputs.
  1010. *
  1011. * @param aType Type of filter node to be created.
  1012. */
  1013. virtual already_AddRefed<FilterNode> CreateFilter(FilterType aType) = 0;
  1014. Matrix GetTransform() const { return mTransform; }
  1015. /*
  1016. * Get the metrics of a glyph, including any additional spacing that is taken
  1017. * during rasterization to this backends (for example because of antialiasing
  1018. * filters.
  1019. *
  1020. * aScaledFont The scaled font used when drawing.
  1021. * aGlyphIndices An array of indices for the glyphs whose the metrics are wanted
  1022. * aNumGlyphs The amount of elements in aGlyphIndices
  1023. * aGlyphMetrics The glyph metrics
  1024. */
  1025. virtual void GetGlyphRasterizationMetrics(ScaledFont *aScaledFont, const uint16_t* aGlyphIndices,
  1026. uint32_t aNumGlyphs, GlyphMetrics* aGlyphMetrics)
  1027. {
  1028. aScaledFont->GetGlyphDesignMetrics(aGlyphIndices, aNumGlyphs, aGlyphMetrics);
  1029. }
  1030. /**
  1031. * Set a transform on the surface, this transform is applied at drawing time
  1032. * to both the mask and source of the operation.
  1033. *
  1034. * Performance note: For some backends it is expensive to change the current
  1035. * transform (because transforms affect a lot of the parts of the pipeline,
  1036. * so new transform change can result in a pipeline flush). To get around
  1037. * this, DrawTarget implementations buffer transform changes and try to only
  1038. * set the current transform on the backend when required. That tracking has
  1039. * its own performance impact though, and ideally callers would be smart
  1040. * enough not to require it. At a future date this method may stop this
  1041. * doing transform buffering so, if you're a consumer, please try to be smart
  1042. * about calling this method as little as possible. For example, instead of
  1043. * concatenating a translation onto the current transform then calling
  1044. * FillRect, try to integrate the translation into FillRect's aRect
  1045. * argument's x/y offset.
  1046. */
  1047. virtual void SetTransform(const Matrix &aTransform)
  1048. { mTransform = aTransform; mTransformDirty = true; }
  1049. inline void ConcatTransform(const Matrix &aTransform)
  1050. { SetTransform(aTransform * Matrix(GetTransform())); }
  1051. SurfaceFormat GetFormat() const { return mFormat; }
  1052. /** Tries to get a native surface for a DrawTarget, this may fail if the
  1053. * draw target cannot convert to this surface type.
  1054. */
  1055. virtual void *GetNativeSurface(NativeSurfaceType aType) { return nullptr; }
  1056. virtual bool IsDualDrawTarget() const { return false; }
  1057. virtual bool IsTiledDrawTarget() const { return false; }
  1058. virtual bool SupportsRegionClipping() const { return true; }
  1059. void AddUserData(UserDataKey *key, void *userData, void (*destroy)(void*)) {
  1060. mUserData.Add(key, userData, destroy);
  1061. }
  1062. void *GetUserData(UserDataKey *key) const {
  1063. return mUserData.Get(key);
  1064. }
  1065. void *RemoveUserData(UserDataKey *key) {
  1066. return mUserData.Remove(key);
  1067. }
  1068. /** Within this rectangle all pixels will be opaque by the time the result of
  1069. * this DrawTarget is first used for drawing. Either by the underlying surface
  1070. * being used as an input to external drawing, or Snapshot() being called.
  1071. * This rectangle is specified in device space.
  1072. */
  1073. void SetOpaqueRect(const IntRect &aRect) {
  1074. mOpaqueRect = aRect;
  1075. }
  1076. const IntRect &GetOpaqueRect() const {
  1077. return mOpaqueRect;
  1078. }
  1079. virtual bool IsCurrentGroupOpaque() {
  1080. return GetFormat() == SurfaceFormat::B8G8R8X8;
  1081. }
  1082. virtual void SetPermitSubpixelAA(bool aPermitSubpixelAA) {
  1083. mPermitSubpixelAA = aPermitSubpixelAA;
  1084. }
  1085. bool GetPermitSubpixelAA() {
  1086. return mPermitSubpixelAA;
  1087. }
  1088. /**
  1089. * Ensures that no snapshot is still pointing to this DrawTarget's surface data.
  1090. *
  1091. * This can be useful if the DrawTarget is wrapped around data that it does not
  1092. * own, and for some reason the owner of the data has to make it temporarily
  1093. * unavailable without the DrawTarget knowing about it.
  1094. * This can cause costly surface copies, so it should not be used without a
  1095. * a good reason.
  1096. */
  1097. virtual void DetachAllSnapshots() = 0;
  1098. #ifdef USE_SKIA_GPU
  1099. virtual bool InitWithGrContext(GrContext* aGrContext,
  1100. const IntSize &aSize,
  1101. SurfaceFormat aFormat)
  1102. {
  1103. MOZ_CRASH("GFX: InitWithGrContext");
  1104. }
  1105. #endif
  1106. protected:
  1107. UserData mUserData;
  1108. Matrix mTransform;
  1109. IntRect mOpaqueRect;
  1110. bool mTransformDirty : 1;
  1111. bool mPermitSubpixelAA : 1;
  1112. SurfaceFormat mFormat;
  1113. };
  1114. class DrawTargetCapture : public DrawTarget
  1115. {
  1116. };
  1117. class DrawEventRecorder : public RefCounted<DrawEventRecorder>
  1118. {
  1119. public:
  1120. MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(DrawEventRecorder)
  1121. virtual ~DrawEventRecorder() { }
  1122. };
  1123. struct Tile
  1124. {
  1125. RefPtr<DrawTarget> mDrawTarget;
  1126. IntPoint mTileOrigin;
  1127. };
  1128. struct TileSet
  1129. {
  1130. Tile* mTiles;
  1131. size_t mTileCount;
  1132. };
  1133. struct Config {
  1134. LogForwarder* mLogForwarder;
  1135. int32_t mMaxTextureSize;
  1136. int32_t mMaxAllocSize;
  1137. Config()
  1138. : mLogForwarder(nullptr)
  1139. , mMaxTextureSize(8192)
  1140. , mMaxAllocSize(52000000)
  1141. {}
  1142. };
  1143. class GFX2D_API Factory
  1144. {
  1145. public:
  1146. static void Init(const Config& aConfig);
  1147. static void ShutDown();
  1148. static bool HasSSE2();
  1149. /**
  1150. * Returns false if any of the following are true:
  1151. *
  1152. * - the width/height of |sz| are less than or equal to zero
  1153. * - the width/height of |sz| are greater than |limit|
  1154. * - the number of bytes that need to be allocated for the surface is too
  1155. * big to fit in an int32_t, or bigger than |allocLimit|, if specifed
  1156. *
  1157. * To calculate the number of bytes that need to be allocated for the surface
  1158. * this function makes the conservative assumption that there need to be
  1159. * 4 bytes-per-pixel, and the stride alignment is 16 bytes.
  1160. *
  1161. * The reason for using int32_t rather than uint32_t is again to be
  1162. * conservative; some code has in the past and may in the future use signed
  1163. * integers to store buffer lengths etc.
  1164. */
  1165. static bool CheckSurfaceSize(const IntSize &sz,
  1166. int32_t limit = 0,
  1167. int32_t allocLimit = 0);
  1168. /**
  1169. * Make sure that the given buffer size doesn't exceed the allocation limit.
  1170. */
  1171. static bool CheckBufferSize(int32_t bufSize);
  1172. /** Make sure the given dimension satisfies the CheckSurfaceSize and is
  1173. * within 8k limit. The 8k value is chosen a bit randomly.
  1174. */
  1175. static bool ReasonableSurfaceSize(const IntSize &aSize);
  1176. static bool AllowedSurfaceSize(const IntSize &aSize);
  1177. static already_AddRefed<DrawTarget> CreateDrawTargetForCairoSurface(cairo_surface_t* aSurface, const IntSize& aSize, SurfaceFormat* aFormat = nullptr);
  1178. static already_AddRefed<SourceSurface> CreateSourceSurfaceForCairoSurface(cairo_surface_t* aSurface, const IntSize& aSize, SurfaceFormat aFormat);
  1179. static already_AddRefed<DrawTarget>
  1180. CreateDrawTarget(BackendType aBackend, const IntSize &aSize, SurfaceFormat aFormat);
  1181. static already_AddRefed<DrawTarget>
  1182. CreateRecordingDrawTarget(DrawEventRecorder *aRecorder, DrawTarget *aDT);
  1183. static already_AddRefed<DrawTarget>
  1184. CreateDrawTargetForData(BackendType aBackend, unsigned char* aData, const IntSize &aSize, int32_t aStride, SurfaceFormat aFormat, bool aUninitialized = false);
  1185. static already_AddRefed<ScaledFont>
  1186. CreateScaledFontForNativeFont(const NativeFont &aNativeFont, Float aSize);
  1187. #ifdef MOZ_WIDGET_GTK
  1188. static already_AddRefed<ScaledFont>
  1189. CreateScaledFontForFontconfigFont(cairo_scaled_font_t* aScaledFont, FcPattern* aPattern, Float aSize);
  1190. #endif
  1191. /**
  1192. * This creates a NativeFontResource from TrueType data.
  1193. *
  1194. * @param aData Pointer to the data
  1195. * @param aSize Size of the TrueType data
  1196. * @param aType Type of NativeFontResource that should be created.
  1197. * @return a NativeFontResource of nullptr if failed.
  1198. */
  1199. static already_AddRefed<NativeFontResource>
  1200. CreateNativeFontResource(uint8_t *aData, uint32_t aSize, FontType aType);
  1201. /**
  1202. * This creates a scaled font with an associated cairo_scaled_font_t, and
  1203. * must be used when using the Cairo backend. The NativeFont and
  1204. * cairo_scaled_font_t* parameters must correspond to the same font.
  1205. */
  1206. static already_AddRefed<ScaledFont>
  1207. CreateScaledFontWithCairo(const NativeFont &aNativeFont, Float aSize, cairo_scaled_font_t* aScaledFont);
  1208. /**
  1209. * This creates a simple data source surface for a certain size. It allocates
  1210. * new memory for the surface. This memory is freed when the surface is
  1211. * destroyed. The caller is responsible for handing the case where nullptr
  1212. * is returned. The surface is not zeroed unless requested.
  1213. */
  1214. static already_AddRefed<DataSourceSurface>
  1215. CreateDataSourceSurface(const IntSize &aSize, SurfaceFormat aFormat, bool aZero = false);
  1216. /**
  1217. * This creates a simple data source surface for a certain size with a
  1218. * specific stride, which must be large enough to fit all pixels.
  1219. * It allocates new memory for the surface. This memory is freed when
  1220. * the surface is destroyed. The caller is responsible for handling the case
  1221. * where nullptr is returned. The surface is not zeroed unless requested.
  1222. */
  1223. static already_AddRefed<DataSourceSurface>
  1224. CreateDataSourceSurfaceWithStride(const IntSize &aSize, SurfaceFormat aFormat, int32_t aStride, bool aZero = false);
  1225. typedef void (*SourceSurfaceDeallocator)(void* aClosure);
  1226. /**
  1227. * This creates a simple data source surface for some existing data. It will
  1228. * wrap this data and the data for this source surface.
  1229. *
  1230. * We can provide a custom destroying function for |aData|. This will be
  1231. * called in the surface dtor using |aDeallocator| and the |aClosure|. If
  1232. * there are errors during construction(return a nullptr surface), the caller
  1233. * is responsible for the deallocation.
  1234. *
  1235. * If there is no destroying function, the caller is responsible for
  1236. * deallocating the aData memory only after destruction of this
  1237. * DataSourceSurface.
  1238. */
  1239. static already_AddRefed<DataSourceSurface>
  1240. CreateWrappingDataSourceSurface(uint8_t *aData,
  1241. int32_t aStride,
  1242. const IntSize &aSize,
  1243. SurfaceFormat aFormat,
  1244. SourceSurfaceDeallocator aDeallocator = nullptr,
  1245. void* aClosure = nullptr);
  1246. static void
  1247. CopyDataSourceSurface(DataSourceSurface* aSource,
  1248. DataSourceSurface* aDest);
  1249. static already_AddRefed<DrawEventRecorder>
  1250. CreateEventRecorderForFile(const char *aFilename);
  1251. static void SetGlobalEventRecorder(DrawEventRecorder *aRecorder);
  1252. static uint32_t GetMaxSurfaceSize(BackendType aType);
  1253. static LogForwarder* GetLogForwarder() { return sConfig ? sConfig->mLogForwarder : nullptr; }
  1254. private:
  1255. static Config* sConfig;
  1256. public:
  1257. #ifdef USE_SKIA_GPU
  1258. static already_AddRefed<DrawTarget>
  1259. CreateDrawTargetSkiaWithGrContext(GrContext* aGrContext,
  1260. const IntSize &aSize,
  1261. SurfaceFormat aFormat);
  1262. #endif
  1263. static void PurgeAllCaches();
  1264. static already_AddRefed<DrawTarget>
  1265. CreateDualDrawTarget(DrawTarget *targetA, DrawTarget *targetB);
  1266. /*
  1267. * This creates a new tiled DrawTarget. When a tiled drawtarget is used the
  1268. * drawing is distributed over number of tiles which may each hold an
  1269. * individual offset. The tiles in the set must each have the same backend
  1270. * and format.
  1271. */
  1272. static already_AddRefed<DrawTarget> CreateTiledDrawTarget(const TileSet& aTileSet);
  1273. static bool DoesBackendSupportDataDrawtarget(BackendType aType);
  1274. #ifdef USE_SKIA
  1275. static already_AddRefed<DrawTarget> CreateDrawTargetWithSkCanvas(SkCanvas* aCanvas);
  1276. #endif
  1277. #ifdef WIN32
  1278. static already_AddRefed<DrawTarget> CreateDrawTargetForD3D11Texture(ID3D11Texture2D *aTexture, SurfaceFormat aFormat);
  1279. /*
  1280. * Attempts to create and install a D2D1 device from the supplied Direct3D11 device.
  1281. * Returns true on success, or false on failure and leaves the D2D1/Direct3D11 devices unset.
  1282. */
  1283. static bool SetDirect3D11Device(ID3D11Device *aDevice);
  1284. static bool SetDWriteFactory(IDWriteFactory *aFactory);
  1285. static ID3D11Device *GetDirect3D11Device();
  1286. static ID2D1Device *GetD2D1Device();
  1287. static IDWriteFactory *GetDWriteFactory();
  1288. static bool SupportsD2D1();
  1289. static already_AddRefed<GlyphRenderingOptions>
  1290. CreateDWriteGlyphRenderingOptions(IDWriteRenderingParams *aParams);
  1291. static uint64_t GetD2DVRAMUsageDrawTarget();
  1292. static uint64_t GetD2DVRAMUsageSourceSurface();
  1293. static void D2DCleanup();
  1294. static already_AddRefed<ScaledFont>
  1295. CreateScaledFontForDWriteFont(IDWriteFontFace* aFontFace,
  1296. const gfxFontStyle* aStyle,
  1297. Float aSize,
  1298. bool aUseEmbeddedBitmap,
  1299. bool aForceGDIMode);
  1300. private:
  1301. static ID2D1Device *mD2D1Device;
  1302. static ID3D11Device *mD3D11Device;
  1303. static IDWriteFactory *mDWriteFactory;
  1304. #endif
  1305. static DrawEventRecorder *mRecorder;
  1306. };
  1307. } // namespace gfx
  1308. } // namespace mozilla
  1309. #endif // _MOZILLA_GFX_2D_H