Merge mozilla-central and tracemonkey. (a=blockers)
[mozilla-central.git] / gfx / layers / Layers.h
blob406d49f29f3cbb1fa706f161c4a3d6e4a81c06d4
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
15 * The Original Code is Mozilla Corporation code.
17 * The Initial Developer of the Original Code is Mozilla Foundation.
18 * Portions created by the Initial Developer are Copyright (C) 2009
19 * the Initial Developer. All Rights Reserved.
21 * Contributor(s):
22 * Robert O'Callahan <robert@ocallahan.org>
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
38 #ifndef GFX_LAYERS_H
39 #define GFX_LAYERS_H
41 #include "gfxTypes.h"
42 #include "gfxASurface.h"
43 #include "nsRegion.h"
44 #include "nsPoint.h"
45 #include "nsRect.h"
46 #include "nsISupportsImpl.h"
47 #include "nsAutoPtr.h"
48 #include "gfx3DMatrix.h"
49 #include "gfxColor.h"
50 #include "gfxPattern.h"
52 #if defined(DEBUG) || defined(PR_LOGGING)
53 # include <stdio.h> // FILE
54 # include "prlog.h"
55 # define MOZ_LAYERS_HAVE_LOG
56 # define MOZ_LAYERS_LOG(_args) \
57 PR_LOG(LayerManager::GetLog(), PR_LOG_DEBUG, _args)
58 #else
59 struct PRLogModuleInfo;
60 # define MOZ_LAYERS_LOG(_args)
61 #endif // if defined(DEBUG) || defined(PR_LOGGING)
63 class gfxContext;
64 class nsPaintEvent;
66 namespace mozilla {
67 namespace gl {
68 class GLContext;
71 namespace layers {
73 class Layer;
74 class ThebesLayer;
75 class ContainerLayer;
76 class ImageLayer;
77 class ColorLayer;
78 class ImageContainer;
79 class CanvasLayer;
80 class ShadowLayer;
81 class ReadbackLayer;
82 class ReadbackProcessor;
83 class SpecificLayerAttributes;
85 /**
86 * The viewport and displayport metrics for the painted frame at the
87 * time of a layer-tree transaction. These metrics are especially
88 * useful for shadow layers, because the metrics values are updated
89 * atomically with new pixels.
91 struct THEBES_API FrameMetrics {
92 public:
93 // We use IDs to identify frames across processes.
94 typedef PRUint64 ViewID;
95 static const ViewID NULL_SCROLL_ID; // This container layer does not scroll.
96 static const ViewID ROOT_SCROLL_ID; // This is the root scroll frame.
97 static const ViewID START_SCROLL_ID; // This is the ID that scrolling subframes
98 // will begin at.
100 FrameMetrics()
101 : mViewport(0, 0, 0, 0)
102 , mContentSize(0, 0)
103 , mViewportScrollOffset(0, 0)
104 , mScrollId(NULL_SCROLL_ID)
107 // Default copy ctor and operator= are fine
109 PRBool operator==(const FrameMetrics& aOther) const
111 return (mViewport == aOther.mViewport &&
112 mViewportScrollOffset == aOther.mViewportScrollOffset &&
113 mDisplayPort == aOther.mDisplayPort &&
114 mScrollId == aOther.mScrollId);
117 PRBool IsDefault() const
119 return (FrameMetrics() == *this);
122 PRBool IsRootScrollable() const
124 return mScrollId == ROOT_SCROLL_ID;
127 PRBool IsScrollable() const
129 return mScrollId != NULL_SCROLL_ID;
132 nsIntRect mViewport;
133 nsIntSize mContentSize;
134 nsIntPoint mViewportScrollOffset;
135 nsIntRect mDisplayPort;
136 ViewID mScrollId;
139 #define MOZ_LAYER_DECL_NAME(n, e) \
140 virtual const char* Name() const { return n; } \
141 virtual LayerType GetType() const { return e; }
144 * Base class for userdata objects attached to layers and layer managers.
146 class THEBES_API LayerUserData {
147 public:
148 virtual ~LayerUserData() {}
152 * Motivation: For truly smooth animation and video playback, we need to
153 * be able to compose frames and render them on a dedicated thread (i.e.
154 * off the main thread where DOM manipulation, script execution and layout
155 * induce difficult-to-bound latency). This requires Gecko to construct
156 * some kind of persistent scene structure (graph or tree) that can be
157 * safely transmitted across threads. We have other scenarios (e.g. mobile
158 * browsing) where retaining some rendered data between paints is desired
159 * for performance, so again we need a retained scene structure.
161 * Our retained scene structure is a layer tree. Each layer represents
162 * content which can be composited onto a destination surface; the root
163 * layer is usually composited into a window, and non-root layers are
164 * composited into their parent layers. Layers have attributes (e.g.
165 * opacity and clipping) that influence their compositing.
167 * We want to support a variety of layer implementations, including
168 * a simple "immediate mode" implementation that doesn't retain any
169 * rendered data between paints (i.e. uses cairo in just the way that
170 * Gecko used it before layers were introduced). But we also don't want
171 * to have bifurcated "layers"/"non-layers" rendering paths in Gecko.
172 * Therefore the layers API is carefully designed to permit maximally
173 * efficient implementation in an "immediate mode" style. See the
174 * BasicLayerManager for such an implementation.
178 * Helper class to manage user data for layers and LayerManagers.
180 class THEBES_API LayerUserDataSet {
181 public:
182 LayerUserDataSet() : mKey(nsnull) {}
184 void Set(void* aKey, LayerUserData* aValue)
186 NS_ASSERTION(!mKey || mKey == aKey,
187 "Multiple LayerUserData objects not supported");
188 mKey = aKey;
189 mValue = aValue;
192 * This can be used anytime. Ownership passes to the caller!
194 LayerUserData* Remove(void* aKey)
196 if (mKey == aKey) {
197 mKey = nsnull;
198 LayerUserData* d = mValue.forget();
199 return d;
201 return nsnull;
204 * This getter can be used anytime.
206 PRBool Has(void* aKey)
208 return mKey == aKey;
211 * This getter can be used anytime. Ownership is retained by this object.
213 LayerUserData* Get(void* aKey)
215 return mKey == aKey ? mValue.get() : nsnull;
219 * Clear out current user data.
221 void Clear()
223 mKey = nsnull;
224 mValue = nsnull;
227 private:
228 void* mKey;
229 nsAutoPtr<LayerUserData> mValue;
233 * A LayerManager controls a tree of layers. All layers in the tree
234 * must use the same LayerManager.
236 * All modifications to a layer tree must happen inside a transaction.
237 * Only the state of the layer tree at the end of a transaction is
238 * rendered. Transactions cannot be nested
240 * Each transaction has two phases:
241 * 1) Construction: layers are created, inserted, removed and have
242 * properties set on them in this phase.
243 * BeginTransaction and BeginTransactionWithTarget start a transaction in
244 * the Construction phase. When the client has finished constructing the layer
245 * tree, it should call EndConstruction() to enter the drawing phase.
246 * 2) Drawing: ThebesLayers are rendered into in this phase, in tree
247 * order. When the client has finished drawing into the ThebesLayers, it should
248 * call EndTransaction to complete the transaction.
250 * All layer API calls happen on the main thread.
252 * Layers are refcounted. The layer manager holds a reference to the
253 * root layer, and each container layer holds a reference to its children.
255 class THEBES_API LayerManager {
256 NS_INLINE_DECL_REFCOUNTING(LayerManager)
258 public:
259 enum LayersBackend {
260 LAYERS_NONE = 0,
261 LAYERS_BASIC,
262 LAYERS_OPENGL,
263 LAYERS_D3D9,
264 LAYERS_D3D10,
265 LAYERS_LAST
268 LayerManager() : mDestroyed(PR_FALSE), mSnapEffectiveTransforms(PR_TRUE)
270 InitLog();
272 virtual ~LayerManager() {}
275 * Release layers and resources held by this layer manager, and mark
276 * it as destroyed. Should do any cleanup necessary in preparation
277 * for its widget going away. After this call, only user data calls
278 * are valid on the layer manager.
280 virtual void Destroy() { mDestroyed = PR_TRUE; mUserData.Clear(); }
281 PRBool IsDestroyed() { return mDestroyed; }
284 * Start a new transaction. Nested transactions are not allowed so
285 * there must be no transaction currently in progress.
286 * This transaction will update the state of the window from which
287 * this LayerManager was obtained.
289 virtual void BeginTransaction() = 0;
291 * Start a new transaction. Nested transactions are not allowed so
292 * there must be no transaction currently in progress.
293 * This transaction will render the contents of the layer tree to
294 * the given target context. The rendering will be complete when
295 * EndTransaction returns.
297 virtual void BeginTransactionWithTarget(gfxContext* aTarget) = 0;
299 * Attempts to end an "empty transaction". There must have been no
300 * changes to the layer tree since the BeginTransaction().
301 * It's possible for this to fail; ThebesLayers may need to be updated
302 * due to VRAM data being lost, for example. In such cases this method
303 * returns false, and the caller must proceed with a normal layer tree
304 * update and EndTransaction.
306 virtual bool EndEmptyTransaction() = 0;
309 * Function called to draw the contents of each ThebesLayer.
310 * aRegionToDraw contains the region that needs to be drawn.
311 * This would normally be a subregion of the visible region.
312 * The callee must draw all of aRegionToDraw. Drawing outside
313 * aRegionToDraw will be clipped out or ignored.
314 * The callee must draw all of aRegionToDraw.
315 * This region is relative to 0,0 in the ThebesLayer.
317 * aRegionToInvalidate contains a region whose contents have been
318 * changed by the layer manager and which must therefore be invalidated.
319 * For example, this could be non-empty if a retained layer internally
320 * switches from RGBA to RGB or back ... we might want to repaint it to
321 * consistently use subpixel-AA or not.
322 * This region is relative to 0,0 in the ThebesLayer.
323 * aRegionToInvalidate may contain areas that are outside
324 * aRegionToDraw; the callee must ensure that these areas are repainted
325 * in the current layer manager transaction or in a later layer
326 * manager transaction.
328 * aContext must not be used after the call has returned.
329 * We guarantee that buffered contents in the visible
330 * region are valid once drawing is complete.
332 * The origin of aContext is 0,0 in the ThebesLayer.
334 typedef void (* DrawThebesLayerCallback)(ThebesLayer* aLayer,
335 gfxContext* aContext,
336 const nsIntRegion& aRegionToDraw,
337 const nsIntRegion& aRegionToInvalidate,
338 void* aCallbackData);
340 * Finish the construction phase of the transaction, perform the
341 * drawing phase, and end the transaction.
342 * During the drawing phase, all ThebesLayers in the tree are
343 * drawn in tree order, exactly once each, except for those layers
344 * where it is known that the visible region is empty.
346 virtual void EndTransaction(DrawThebesLayerCallback aCallback,
347 void* aCallbackData) = 0;
349 PRBool IsSnappingEffectiveTransforms() { return mSnapEffectiveTransforms; }
352 * CONSTRUCTION PHASE ONLY
353 * Set the root layer. The root layer is initially null. If there is
354 * no root layer, EndTransaction won't draw anything.
356 virtual void SetRoot(Layer* aLayer) = 0;
358 * Can be called anytime
360 Layer* GetRoot() { return mRoot; }
363 * CONSTRUCTION PHASE ONLY
364 * Called when a managee has mutated.
365 * Subclasses overriding this method must first call their
366 * superclass's impl
368 #ifdef DEBUG
369 // In debug builds, we check some properties of |aLayer|.
370 virtual void Mutated(Layer* aLayer);
371 #else
372 virtual void Mutated(Layer* aLayer) { }
373 #endif
376 * CONSTRUCTION PHASE ONLY
377 * Create a ThebesLayer for this manager's layer tree.
379 virtual already_AddRefed<ThebesLayer> CreateThebesLayer() = 0;
381 * CONSTRUCTION PHASE ONLY
382 * Create a ContainerLayer for this manager's layer tree.
384 virtual already_AddRefed<ContainerLayer> CreateContainerLayer() = 0;
386 * CONSTRUCTION PHASE ONLY
387 * Create an ImageLayer for this manager's layer tree.
389 virtual already_AddRefed<ImageLayer> CreateImageLayer() = 0;
391 * CONSTRUCTION PHASE ONLY
392 * Create a ColorLayer for this manager's layer tree.
394 virtual already_AddRefed<ColorLayer> CreateColorLayer() = 0;
396 * CONSTRUCTION PHASE ONLY
397 * Create a CanvasLayer for this manager's layer tree.
399 virtual already_AddRefed<CanvasLayer> CreateCanvasLayer() = 0;
401 * CONSTRUCTION PHASE ONLY
402 * Create a ReadbackLayer for this manager's layer tree.
404 virtual already_AddRefed<ReadbackLayer> CreateReadbackLayer() { return nsnull; }
407 * Can be called anytime
409 virtual already_AddRefed<ImageContainer> CreateImageContainer() = 0;
412 * Type of layer manager his is. This is to be used sparsely in order to
413 * avoid a lot of Layers backend specific code. It should be used only when
414 * Layers backend specific functionality is necessary.
416 virtual LayersBackend GetBackendType() = 0;
419 * Creates a layer which is optimized for inter-operating with this layer
420 * manager.
422 virtual already_AddRefed<gfxASurface>
423 CreateOptimalSurface(const gfxIntSize &aSize,
424 gfxASurface::gfxImageFormat imageFormat);
427 * Return the name of the layer manager's backend.
429 virtual void GetBackendName(nsAString& aName) = 0;
432 * This setter can be used anytime. The user data for all keys is
433 * initially null. Ownership pases to the layer manager.
435 void SetUserData(void* aKey, LayerUserData* aData)
436 { mUserData.Set(aKey, aData); }
438 * This can be used anytime. Ownership passes to the caller!
440 nsAutoPtr<LayerUserData> RemoveUserData(void* aKey)
441 { nsAutoPtr<LayerUserData> d(mUserData.Remove(aKey)); return d; }
443 * This getter can be used anytime.
445 PRBool HasUserData(void* aKey)
446 { return mUserData.Has(aKey); }
448 * This getter can be used anytime. Ownership is retained by the layer
449 * manager.
451 LayerUserData* GetUserData(void* aKey)
452 { return mUserData.Get(aKey); }
454 // We always declare the following logging symbols, because it's
455 // extremely tricky to conditionally declare them. However, for
456 // ifndef MOZ_LAYERS_HAVE_LOG builds, they only have trivial
457 // definitions in Layers.cpp.
458 virtual const char* Name() const { return "???"; }
461 * Dump information about this layer manager and its managed tree to
462 * aFile, which defaults to stderr.
464 void Dump(FILE* aFile=NULL, const char* aPrefix="");
466 * Dump information about just this layer manager itself to aFile,
467 * which defaults to stderr.
469 void DumpSelf(FILE* aFile=NULL, const char* aPrefix="");
472 * Log information about this layer manager and its managed tree to
473 * the NSPR log (if enabled for "Layers").
475 void Log(const char* aPrefix="");
477 * Log information about just this layer manager itself to the NSPR
478 * log (if enabled for "Layers").
480 void LogSelf(const char* aPrefix="");
482 static bool IsLogEnabled();
483 static PRLogModuleInfo* GetLog() { return sLog; }
485 PRBool IsCompositingCheap(LayerManager::LayersBackend aBackend)
486 { return LAYERS_BASIC != aBackend; }
488 virtual PRBool IsCompositingCheap() { return PR_TRUE; }
490 protected:
491 nsRefPtr<Layer> mRoot;
492 LayerUserDataSet mUserData;
493 PRPackedBool mDestroyed;
494 PRPackedBool mSnapEffectiveTransforms;
496 // Print interesting information about this into aTo. Internally
497 // used to implement Dump*() and Log*().
498 virtual nsACString& PrintInfo(nsACString& aTo, const char* aPrefix);
500 static void InitLog();
501 static PRLogModuleInfo* sLog;
504 class ThebesLayer;
507 * A Layer represents anything that can be rendered onto a destination
508 * surface.
510 class THEBES_API Layer {
511 NS_INLINE_DECL_REFCOUNTING(Layer)
513 public:
514 // Keep these in alphabetical order
515 enum LayerType {
516 TYPE_CANVAS,
517 TYPE_COLOR,
518 TYPE_CONTAINER,
519 TYPE_IMAGE,
520 TYPE_READBACK,
521 TYPE_SHADOW,
522 TYPE_THEBES
525 virtual ~Layer() {}
528 * Returns the LayerManager this Layer belongs to. Note that the layer
529 * manager might be in a destroyed state, at which point it's only
530 * valid to set/get user data from it.
532 LayerManager* Manager() { return mManager; }
534 enum {
536 * If this is set, the caller is promising that by the end of this
537 * transaction the entire visible region (as specified by
538 * SetVisibleRegion) will be filled with opaque content.
540 CONTENT_OPAQUE = 0x01,
542 * If this is set, the caller is notifying that the contents of this layer
543 * require per-component alpha for optimal fidelity. However, there is no
544 * guarantee that component alpha will be supported for this layer at
545 * paint time.
546 * This should never be set at the same time as CONTENT_OPAQUE.
548 CONTENT_COMPONENT_ALPHA = 0x02
551 * CONSTRUCTION PHASE ONLY
552 * This lets layout make some promises about what will be drawn into the
553 * visible region of the ThebesLayer. This enables internal quality
554 * and performance optimizations.
556 void SetContentFlags(PRUint32 aFlags)
558 NS_ASSERTION((aFlags & (CONTENT_OPAQUE | CONTENT_COMPONENT_ALPHA)) !=
559 (CONTENT_OPAQUE | CONTENT_COMPONENT_ALPHA),
560 "Can't be opaque and require component alpha");
561 mContentFlags = aFlags;
562 Mutated();
565 * CONSTRUCTION PHASE ONLY
566 * Tell this layer which region will be visible. The visible region
567 * is a region which contains all the contents of the layer that can
568 * actually affect the rendering of the window. It can exclude areas
569 * that are covered by opaque contents of other layers, and it can
570 * exclude areas where this layer simply contains no content at all.
571 * (This can be an overapproximation to the "true" visible region.)
573 * There is no general guarantee that drawing outside the bounds of the
574 * visible region will be ignored. So if a layer draws outside the bounds
575 * of its visible region, it needs to ensure that what it draws is valid.
577 virtual void SetVisibleRegion(const nsIntRegion& aRegion)
579 mVisibleRegion = aRegion;
580 Mutated();
584 * CONSTRUCTION PHASE ONLY
585 * Set the opacity which will be applied to this layer as it
586 * is composited to the destination.
588 void SetOpacity(float aOpacity)
590 mOpacity = aOpacity;
591 Mutated();
595 * CONSTRUCTION PHASE ONLY
596 * Set a clip rect which will be applied to this layer as it is
597 * composited to the destination. The coordinates are relative to
598 * the parent layer (i.e. the contents of this layer
599 * are transformed before this clip rect is applied).
600 * For the root layer, the coordinates are relative to the widget,
601 * in device pixels.
602 * If aRect is null no clipping will be performed.
604 void SetClipRect(const nsIntRect* aRect)
606 mUseClipRect = aRect != nsnull;
607 if (aRect) {
608 mClipRect = *aRect;
610 Mutated();
614 * CONSTRUCTION PHASE ONLY
615 * Set a clip rect which will be applied to this layer as it is
616 * composited to the destination. The coordinates are relative to
617 * the parent layer (i.e. the contents of this layer
618 * are transformed before this clip rect is applied).
619 * For the root layer, the coordinates are relative to the widget,
620 * in device pixels.
621 * The provided rect is intersected with any existing clip rect.
623 void IntersectClipRect(const nsIntRect& aRect)
625 if (mUseClipRect) {
626 mClipRect.IntersectRect(mClipRect, aRect);
627 } else {
628 mUseClipRect = PR_TRUE;
629 mClipRect = aRect;
631 Mutated();
635 * CONSTRUCTION PHASE ONLY
636 * Tell this layer what its transform should be. The transformation
637 * is applied when compositing the layer into its parent container.
638 * XXX Currently only transformations corresponding to 2D affine transforms
639 * are supported.
641 void SetTransform(const gfx3DMatrix& aMatrix)
643 mTransform = aMatrix;
644 Mutated();
648 * CONSTRUCTION PHASE ONLY
650 * Define a subrect of this layer that will be used as the source
651 * image for tiling this layer's visible region. The coordinates
652 * are in the un-transformed space of this layer (i.e. the visible
653 * region of this this layer is tiled before being transformed).
654 * The visible region is tiled "outwards" from the source rect; that
655 * is, the source rect is drawn "in place", then repeated to cover
656 * the layer's visible region.
658 * The interpretation of the source rect varies depending on
659 * underlying layer type. For ImageLayers and CanvasLayers, it
660 * doesn't make sense to set a source rect not fully contained by
661 * the bounds of their underlying images. For ThebesLayers, thebes
662 * content may need to be rendered to fill the source rect. For
663 * ColorLayers, a source rect for tiling doesn't make sense at all.
665 * If aRect is null no tiling will be performed.
667 * NB: this interface is only implemented for BasicImageLayers, and
668 * then only for source rects the same size as the layers'
669 * underlying images.
671 void SetTileSourceRect(const nsIntRect* aRect)
673 mUseTileSourceRect = aRect != nsnull;
674 if (aRect) {
675 mTileSourceRect = *aRect;
677 Mutated();
680 // These getters can be used anytime.
681 float GetOpacity() { return mOpacity; }
682 const nsIntRect* GetClipRect() { return mUseClipRect ? &mClipRect : nsnull; }
683 PRUint32 GetContentFlags() { return mContentFlags; }
684 const nsIntRegion& GetVisibleRegion() { return mVisibleRegion; }
685 ContainerLayer* GetParent() { return mParent; }
686 Layer* GetNextSibling() { return mNextSibling; }
687 Layer* GetPrevSibling() { return mPrevSibling; }
688 virtual Layer* GetFirstChild() { return nsnull; }
689 virtual Layer* GetLastChild() { return nsnull; }
690 const gfx3DMatrix& GetTransform() { return mTransform; }
691 const nsIntRect* GetTileSourceRect() { return mUseTileSourceRect ? &mTileSourceRect : nsnull; }
694 * DRAWING PHASE ONLY
696 * Write layer-subtype-specific attributes into aAttrs. Used to
697 * synchronize layer attributes to their shadows'.
699 virtual void FillSpecificAttributes(SpecificLayerAttributes& aAttrs) { }
701 // Returns true if it's OK to save the contents of aLayer in an
702 // opaque surface (a surface without an alpha channel).
703 // If we can use a surface without an alpha channel, we should, because
704 // it will often make painting of antialiased text faster and higher
705 // quality.
706 PRBool CanUseOpaqueSurface();
708 enum SurfaceMode {
709 SURFACE_OPAQUE,
710 SURFACE_SINGLE_CHANNEL_ALPHA,
711 SURFACE_COMPONENT_ALPHA
713 SurfaceMode GetSurfaceMode()
715 if (CanUseOpaqueSurface())
716 return SURFACE_OPAQUE;
717 if (mContentFlags & CONTENT_COMPONENT_ALPHA)
718 return SURFACE_COMPONENT_ALPHA;
719 return SURFACE_SINGLE_CHANNEL_ALPHA;
723 * This setter can be used anytime. The user data for all keys is
724 * initially null. Ownership pases to the layer manager.
726 void SetUserData(void* aKey, LayerUserData* aData)
727 { mUserData.Set(aKey, aData); }
729 * This can be used anytime. Ownership passes to the caller!
731 nsAutoPtr<LayerUserData> RemoveUserData(void* aKey)
732 { nsAutoPtr<LayerUserData> d(mUserData.Remove(aKey)); return d; }
734 * This getter can be used anytime.
736 PRBool HasUserData(void* aKey)
737 { return mUserData.Has(aKey); }
739 * This getter can be used anytime. Ownership is retained by the layer
740 * manager.
742 LayerUserData* GetUserData(void* aKey)
743 { return mUserData.Get(aKey); }
746 * |Disconnect()| is used by layers hooked up over IPC. It may be
747 * called at any time, and may not be called at all. Using an
748 * IPC-enabled layer after Destroy() (drawing etc.) results in a
749 * safe no-op; no crashy or uaf etc.
751 * XXX: this interface is essentially LayerManager::Destroy, but at
752 * Layer granularity. It might be beneficial to unify them.
754 virtual void Disconnect() {}
757 * Dynamic downcast to a Thebes layer. Returns null if this is not
758 * a ThebesLayer.
760 virtual ThebesLayer* AsThebesLayer() { return nsnull; }
763 * Dynamic cast to a ShadowLayer. Return null if this is not a
764 * ShadowLayer. Can be used anytime.
766 virtual ShadowLayer* AsShadowLayer() { return nsnull; }
768 // These getters can be used anytime. They return the effective
769 // values that should be used when drawing this layer to screen,
770 // accounting for this layer possibly being a shadow.
771 const nsIntRect* GetEffectiveClipRect();
772 const nsIntRegion& GetEffectiveVisibleRegion();
774 * Returns the product of the opacities of this layer and all ancestors up
775 * to and excluding the nearest ancestor that has UseIntermediateSurface() set.
777 float GetEffectiveOpacity();
779 * This returns the effective transform computed by
780 * ComputeEffectiveTransforms. Typically this is a transform that transforms
781 * this layer all the way to some intermediate surface or destination
782 * surface. For non-BasicLayers this will be a transform to the nearest
783 * ancestor with UseIntermediateSurface() (or to the root, if there is no
784 * such ancestor), but for BasicLayers it's different.
786 const gfx3DMatrix& GetEffectiveTransform() const { return mEffectiveTransform; }
789 * @param aTransformToSurface the composition of the transforms
790 * from the parent layer (if any) to the destination pixel grid.
792 * Computes mEffectiveTransform for this layer and all its descendants.
793 * mEffectiveTransform transforms this layer up to the destination
794 * pixel grid (whatever aTransformToSurface is relative to).
796 * We promise that when this is called on a layer, all ancestor layers
797 * have already had ComputeEffectiveTransforms called.
799 virtual void ComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface) = 0;
801 virtual const char* Name() const =0;
802 virtual LayerType GetType() const =0;
805 * Only the implementation should call this. This is per-implementation
806 * private data. Normally, all layers with a given layer manager
807 * use the same type of ImplData.
809 void* ImplData() { return mImplData; }
812 * Only the implementation should use these methods.
814 void SetParent(ContainerLayer* aParent) { mParent = aParent; }
815 void SetNextSibling(Layer* aSibling) { mNextSibling = aSibling; }
816 void SetPrevSibling(Layer* aSibling) { mPrevSibling = aSibling; }
819 * Dump information about this layer manager and its managed tree to
820 * aFile, which defaults to stderr.
822 void Dump(FILE* aFile=NULL, const char* aPrefix="");
824 * Dump information about just this layer manager itself to aFile,
825 * which defaults to stderr.
827 void DumpSelf(FILE* aFile=NULL, const char* aPrefix="");
830 * Log information about this layer manager and its managed tree to
831 * the NSPR log (if enabled for "Layers").
833 void Log(const char* aPrefix="");
835 * Log information about just this layer manager itself to the NSPR
836 * log (if enabled for "Layers").
838 void LogSelf(const char* aPrefix="");
840 static bool IsLogEnabled() { return LayerManager::IsLogEnabled(); }
842 protected:
843 Layer(LayerManager* aManager, void* aImplData) :
844 mManager(aManager),
845 mParent(nsnull),
846 mNextSibling(nsnull),
847 mPrevSibling(nsnull),
848 mImplData(aImplData),
849 mOpacity(1.0),
850 mContentFlags(0),
851 mUseClipRect(PR_FALSE),
852 mUseTileSourceRect(PR_FALSE)
855 void Mutated() { mManager->Mutated(this); }
857 // Print interesting information about this into aTo. Internally
858 // used to implement Dump*() and Log*(). If subclasses have
859 // additional interesting properties, they should override this with
860 // an implementation that first calls the base implementation then
861 // appends additional info to aTo.
862 virtual nsACString& PrintInfo(nsACString& aTo, const char* aPrefix);
865 * Returns the local transform for this layer: either mTransform or,
866 * for shadow layers, GetShadowTransform()
868 const gfx3DMatrix& GetLocalTransform();
871 * Computes a tweaked version of aTransform that snaps a point or a rectangle
872 * to pixel boundaries. Snapping is only performed if this layer's
873 * layer manager has enabled snapping (which is the default).
874 * @param aSnapRect a rectangle whose edges should be snapped to pixel
875 * boundaries in the destination surface. If the rectangle is empty,
876 * then the snapping process should preserve the scale factors of the
877 * transform matrix
878 * @param aResidualTransform a transform to apply before mEffectiveTransform
879 * in order to get the results to completely match aTransform
881 gfx3DMatrix SnapTransform(const gfx3DMatrix& aTransform,
882 const gfxRect& aSnapRect,
883 gfxMatrix* aResidualTransform);
885 LayerManager* mManager;
886 ContainerLayer* mParent;
887 Layer* mNextSibling;
888 Layer* mPrevSibling;
889 void* mImplData;
890 LayerUserDataSet mUserData;
891 nsIntRegion mVisibleRegion;
892 gfx3DMatrix mTransform;
893 gfx3DMatrix mEffectiveTransform;
894 float mOpacity;
895 nsIntRect mClipRect;
896 nsIntRect mTileSourceRect;
897 PRUint32 mContentFlags;
898 PRPackedBool mUseClipRect;
899 PRPackedBool mUseTileSourceRect;
903 * A Layer which we can draw into using Thebes. It is a conceptually
904 * infinite surface, but each ThebesLayer has an associated "valid region"
905 * of contents that it is currently storing, which is finite. ThebesLayer
906 * implementations can store content between paints.
908 * ThebesLayers are rendered into during the drawing phase of a transaction.
910 * Currently the contents of a ThebesLayer are in the device output color
911 * space.
913 class THEBES_API ThebesLayer : public Layer {
914 public:
916 * CONSTRUCTION PHASE ONLY
917 * Tell this layer that the content in some region has changed and
918 * will need to be repainted. This area is removed from the valid
919 * region.
921 virtual void InvalidateRegion(const nsIntRegion& aRegion) = 0;
924 * Can be used anytime
926 const nsIntRegion& GetValidRegion() const { return mValidRegion; }
927 float GetXResolution() const { return mXResolution; }
928 float GetYResolution() const { return mYResolution; }
930 virtual ThebesLayer* AsThebesLayer() { return this; }
932 MOZ_LAYER_DECL_NAME("ThebesLayer", TYPE_THEBES)
934 virtual void ComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface)
936 // The default implementation just snaps 0,0 to pixels.
937 gfx3DMatrix idealTransform = GetLocalTransform()*aTransformToSurface;
938 mEffectiveTransform = SnapTransform(idealTransform, gfxRect(0, 0, 0, 0), nsnull);
941 bool UsedForReadback() { return mUsedForReadback; }
942 void SetUsedForReadback(bool aUsed) { mUsedForReadback = aUsed; }
944 protected:
945 ThebesLayer(LayerManager* aManager, void* aImplData)
946 : Layer(aManager, aImplData)
947 , mValidRegion()
948 , mXResolution(1.0)
949 , mYResolution(1.0)
950 , mUsedForReadback(false)
952 mContentFlags = 0; // Clear NO_TEXT, NO_TEXT_OVER_TRANSPARENT
955 virtual nsACString& PrintInfo(nsACString& aTo, const char* aPrefix);
957 nsIntRegion mValidRegion;
958 // Resolution values tell this to paint its content scaled by
959 // <aXResolution, aYResolution>, into a backing buffer with
960 // dimensions scaled the same. A non-1.0 resolution also tells this
961 // to set scaling factors that compensate for the re-paint
962 // resolution when rendering itself to render targets
964 // Resolution doesn't affect the visible region, valid region, or
965 // re-painted regions at all. It only affects how scalable thebes
966 // content is rasterized to device pixels.
968 // Setting the resolution isn't part of the public ThebesLayer API
969 // because it's backend-specific, and it doesn't necessarily make
970 // sense for all backends to fully support it.
971 float mXResolution;
972 float mYResolution;
974 * Set when this ThebesLayer is participating in readback, i.e. some
975 * ReadbackLayer (may) be getting its background from this layer.
977 bool mUsedForReadback;
981 * A Layer which other layers render into. It holds references to its
982 * children.
984 class THEBES_API ContainerLayer : public Layer {
985 public:
987 * CONSTRUCTION PHASE ONLY
988 * Insert aChild into the child list of this container. aChild must
989 * not be currently in any child list or the root for the layer manager.
990 * If aAfter is non-null, it must be a child of this container and
991 * we insert after that layer. If it's null we insert at the start.
993 virtual void InsertAfter(Layer* aChild, Layer* aAfter) = 0;
995 * CONSTRUCTION PHASE ONLY
996 * Remove aChild from the child list of this container. aChild must
997 * be a child of this container.
999 virtual void RemoveChild(Layer* aChild) = 0;
1002 * CONSTRUCTION PHASE ONLY
1003 * Set the (sub)document metrics used to render the Layer subtree
1004 * rooted at this.
1006 void SetFrameMetrics(const FrameMetrics& aFrameMetrics)
1008 mFrameMetrics = aFrameMetrics;
1011 // These getters can be used anytime.
1013 virtual Layer* GetFirstChild() { return mFirstChild; }
1014 virtual Layer* GetLastChild() { return mLastChild; }
1015 const FrameMetrics& GetFrameMetrics() { return mFrameMetrics; }
1017 MOZ_LAYER_DECL_NAME("ContainerLayer", TYPE_CONTAINER)
1020 * ContainerLayer backends need to override ComputeEffectiveTransforms
1021 * since the decision about whether to use a temporary surface for the
1022 * container is backend-specific. ComputeEffectiveTransforms must also set
1023 * mUseIntermediateSurface.
1025 virtual void ComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface) = 0;
1028 * Call this only after ComputeEffectiveTransforms has been invoked
1029 * on this layer.
1030 * Returns true if this will use an intermediate surface. This is largely
1031 * backend-dependent, but it affects the operation of GetEffectiveOpacity().
1033 PRBool UseIntermediateSurface() { return mUseIntermediateSurface; }
1036 * Returns true if this container has more than one non-empty child
1038 PRBool HasMultipleChildren();
1041 * Returns true if this container supports children with component alpha.
1042 * Should only be called while painting a child of this layer.
1044 PRBool SupportsComponentAlphaChildren() { return mSupportsComponentAlphaChildren; }
1046 protected:
1047 friend class ReadbackProcessor;
1049 void DidInsertChild(Layer* aLayer);
1050 void DidRemoveChild(Layer* aLayer);
1052 ContainerLayer(LayerManager* aManager, void* aImplData)
1053 : Layer(aManager, aImplData),
1054 mFirstChild(nsnull),
1055 mLastChild(nsnull),
1056 mUseIntermediateSurface(PR_FALSE),
1057 mSupportsComponentAlphaChildren(PR_FALSE),
1058 mMayHaveReadbackChild(PR_FALSE)
1060 mContentFlags = 0; // Clear NO_TEXT, NO_TEXT_OVER_TRANSPARENT
1064 * A default implementation of ComputeEffectiveTransforms for use by OpenGL
1065 * and D3D.
1067 void DefaultComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface);
1070 * Loops over the children calling ComputeEffectiveTransforms on them.
1072 void ComputeEffectiveTransformsForChildren(const gfx3DMatrix& aTransformToSurface);
1074 virtual nsACString& PrintInfo(nsACString& aTo, const char* aPrefix);
1076 Layer* mFirstChild;
1077 Layer* mLastChild;
1078 FrameMetrics mFrameMetrics;
1079 PRPackedBool mUseIntermediateSurface;
1080 PRPackedBool mSupportsComponentAlphaChildren;
1081 PRPackedBool mMayHaveReadbackChild;
1085 * A Layer which just renders a solid color in its visible region. It actually
1086 * can fill any area that contains the visible region, so if you need to
1087 * restrict the area filled, set a clip region on this layer.
1089 class THEBES_API ColorLayer : public Layer {
1090 public:
1092 * CONSTRUCTION PHASE ONLY
1093 * Set the color of the layer.
1095 virtual void SetColor(const gfxRGBA& aColor)
1097 mColor = aColor;
1100 // This getter can be used anytime.
1101 virtual const gfxRGBA& GetColor() { return mColor; }
1103 MOZ_LAYER_DECL_NAME("ColorLayer", TYPE_COLOR)
1105 virtual void ComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface)
1107 // Snap 0,0 to pixel boundaries, no extra internal transform.
1108 gfx3DMatrix idealTransform = GetLocalTransform()*aTransformToSurface;
1109 mEffectiveTransform = SnapTransform(idealTransform, gfxRect(0, 0, 0, 0), nsnull);
1112 protected:
1113 ColorLayer(LayerManager* aManager, void* aImplData)
1114 : Layer(aManager, aImplData),
1115 mColor(0.0, 0.0, 0.0, 0.0)
1118 virtual nsACString& PrintInfo(nsACString& aTo, const char* aPrefix);
1120 gfxRGBA mColor;
1124 * A Layer for HTML Canvas elements. It's backed by either a
1125 * gfxASurface or a GLContext (for WebGL layers), and has some control
1126 * for intelligent updating from the source if necessary (for example,
1127 * if hardware compositing is not available, for reading from the GL
1128 * buffer into an image surface that we can layer composite.)
1130 * After Initialize is called, the underlying canvas Surface/GLContext
1131 * must not be modified during a layer transaction.
1133 class THEBES_API CanvasLayer : public Layer {
1134 public:
1135 struct Data {
1136 Data()
1137 : mSurface(nsnull), mGLContext(nsnull),
1138 mGLBufferIsPremultiplied(PR_FALSE)
1141 /* One of these two must be specified, but never both */
1142 gfxASurface* mSurface; // a gfx Surface for the canvas contents
1143 mozilla::gl::GLContext* mGLContext; // a GL PBuffer Context
1145 /* The size of the canvas content */
1146 nsIntSize mSize;
1148 /* Whether the GLContext contains premultiplied alpha
1149 * values in the framebuffer or not. Defaults to FALSE.
1151 PRPackedBool mGLBufferIsPremultiplied;
1155 * CONSTRUCTION PHASE ONLY
1156 * Initialize this CanvasLayer with the given data. The data must
1157 * have either mSurface or mGLContext initialized (but not both), as
1158 * well as mSize.
1160 * This must only be called once.
1162 virtual void Initialize(const Data& aData) = 0;
1165 * CONSTRUCTION PHASE ONLY
1166 * Notify this CanvasLayer that the rectangle given by aRect
1167 * has been updated, and any work that needs to be done
1168 * to bring the contents from the Surface/GLContext to the
1169 * Layer in preparation for compositing should be performed.
1171 virtual void Updated(const nsIntRect& aRect) = 0;
1174 * CONSTRUCTION PHASE ONLY
1175 * Set the filter used to resample this image (if necessary).
1177 void SetFilter(gfxPattern::GraphicsFilter aFilter) { mFilter = aFilter; }
1178 gfxPattern::GraphicsFilter GetFilter() const { return mFilter; }
1180 MOZ_LAYER_DECL_NAME("CanvasLayer", TYPE_CANVAS)
1182 virtual void ComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface)
1184 // Snap our local transform first, and snap the inherited transform as well.
1185 // This makes our snapping equivalent to what would happen if our content
1186 // was drawn into a ThebesLayer (gfxContext would snap using the local
1187 // transform, then we'd snap again when compositing the ThebesLayer).
1188 mEffectiveTransform =
1189 SnapTransform(GetLocalTransform(), gfxRect(0, 0, mBounds.width, mBounds.height),
1190 nsnull)*
1191 SnapTransform(aTransformToSurface, gfxRect(0, 0, 0, 0), nsnull);
1194 protected:
1195 CanvasLayer(LayerManager* aManager, void* aImplData)
1196 : Layer(aManager, aImplData), mFilter(gfxPattern::FILTER_GOOD) {}
1198 virtual nsACString& PrintInfo(nsACString& aTo, const char* aPrefix);
1201 * 0, 0, canvaswidth, canvasheight
1203 nsIntRect mBounds;
1204 gfxPattern::GraphicsFilter mFilter;
1210 #endif /* GFX_LAYERS_H */