Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/gfx/layers/Layers.h
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
 * License, v. 2.0. If a copy of the MPL was not distributed with this
5
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#ifndef GFX_LAYERS_H
8
#define GFX_LAYERS_H
9
10
#include <map>
11
#include <stdint.h>                     // for uint32_t, uint64_t, uint8_t
12
#include <stdio.h>                      // for FILE
13
#include <sys/types.h>                  // for int32_t
14
#include "FrameMetrics.h"               // for FrameMetrics
15
#include "Units.h"                      // for LayerMargin, LayerPoint, ParentLayerIntRect
16
#include "gfxContext.h"
17
#include "gfxTypes.h"
18
#include "gfxPoint.h"                   // for gfxPoint
19
#include "gfxRect.h"                    // for gfxRect
20
#include "gfx2DGlue.h"
21
#include "mozilla/Assertions.h"         // for MOZ_ASSERT_HELPER2, etc
22
#include "mozilla/Array.h"
23
#include "mozilla/DebugOnly.h"          // for DebugOnly
24
#include "mozilla/EventForwards.h"      // for nsPaintEvent
25
#include "mozilla/Maybe.h"              // for Maybe
26
#include "mozilla/Poison.h"
27
#include "mozilla/RefPtr.h"             // for already_AddRefed
28
#include "mozilla/TimeStamp.h"          // for TimeStamp, TimeDuration
29
#include "mozilla/UniquePtr.h"          // for UniquePtr
30
#include "mozilla/gfx/BaseMargin.h"     // for BaseMargin
31
#include "mozilla/gfx/BasePoint.h"      // for BasePoint
32
#include "mozilla/gfx/Point.h"          // for IntSize
33
#include "mozilla/gfx/TiledRegion.h"    // for TiledIntRegion
34
#include "mozilla/gfx/Types.h"          // for SurfaceFormat
35
#include "mozilla/gfx/UserData.h"       // for UserData, etc
36
#include "mozilla/layers/AnimationInfo.h" // for AnimationInfo
37
#include "mozilla/layers/BSPTree.h"     // for LayerPolygon
38
#include "mozilla/layers/CanvasRenderer.h"
39
#include "mozilla/layers/LayerAttributes.h"
40
#include "mozilla/layers/LayersTypes.h"
41
#include "mozilla/mozalloc.h"           // for operator delete, etc
42
#include "nsAutoPtr.h"                  // for nsAutoPtr, nsRefPtr, etc
43
#include "nsCOMPtr.h"                   // for already_AddRefed
44
#include "nsCSSPropertyID.h"              // for nsCSSPropertyID
45
#include "nsDebug.h"                    // for NS_ASSERTION
46
#include "nsISupportsImpl.h"            // for Layer::Release, etc
47
#include "nsRect.h"                     // for mozilla::gfx::IntRect
48
#include "nsRegion.h"                   // for nsIntRegion
49
#include "nsString.h"                   // for nsCString
50
#include "nsTArray.h"                   // for nsTArray
51
#include "nsTArrayForwardDeclare.h"     // for InfallibleTArray
52
#include "nscore.h"                     // for nsACString, nsAString
53
#include "mozilla/Logging.h"                      // for PRLogModuleInfo
54
#include "nsIWidget.h"                  // For plugin window configuration information structs
55
#include "ImageContainer.h"
56
57
class gfxContext;
58
class nsDisplayListBuilder;
59
class nsDisplayItem;
60
61
extern uint8_t gLayerManagerLayerBuilder;
62
63
namespace mozilla {
64
65
class ComputedTimingFunction;
66
class FrameLayerBuilder;
67
68
namespace gl {
69
class GLContext;
70
} // namespace gl
71
72
namespace gfx {
73
class DrawTarget;
74
} // namespace gfx
75
76
namespace layers {
77
78
class Animation;
79
class AsyncCanvasRenderer;
80
class AsyncPanZoomController;
81
class BasicLayerManager;
82
class ClientLayerManager;
83
class HostLayerManager;
84
class Layer;
85
class LayerMetricsWrapper;
86
class PaintedLayer;
87
class ContainerLayer;
88
class ImageLayer;
89
class ColorLayer;
90
class CompositorAnimations;
91
class CompositorBridgeChild;
92
class CanvasLayer;
93
class ReadbackLayer;
94
class ReadbackProcessor;
95
class RefLayer;
96
class HostLayer;
97
class FocusTarget;
98
class KnowsCompositor;
99
class ShadowableLayer;
100
class ShadowLayerForwarder;
101
class LayerManagerComposite;
102
class SpecificLayerAttributes;
103
class TransactionIdAllocator;
104
class Compositor;
105
class FrameUniformityData;
106
class PersistentBufferProvider;
107
class GlyphArray;
108
class WebRenderLayerManager;
109
struct AnimData;
110
111
namespace layerscope {
112
class LayersPacket;
113
} // namespace layerscope
114
115
#define MOZ_LAYER_DECL_NAME(n, e)                              \
116
0
  virtual const char* Name() const override { return n; }  \
Unexecuted instantiation: mozilla::layers::ImageLayer::Name() const
Unexecuted instantiation: mozilla::layers::PaintedLayerMLGPU::Name() const
117
0
  virtual LayerType GetType() const override { return e; } \
Unexecuted instantiation: mozilla::layers::ImageLayer::GetType() const
Unexecuted instantiation: mozilla::layers::PaintedLayerMLGPU::GetType() const
118
0
  static LayerType Type() { return e; }
Unexecuted instantiation: mozilla::layers::ReadbackLayer::Type()
Unexecuted instantiation: mozilla::layers::RefLayerMLGPU::Type()
Unexecuted instantiation: mozilla::layers::ColorLayerMLGPU::Type()
Unexecuted instantiation: mozilla::layers::PaintedLayerMLGPU::Type()
Unexecuted instantiation: mozilla::layers::ContainerLayerMLGPU::Type()
Unexecuted instantiation: mozilla::layers::ImageLayerMLGPU::Type()
119
120
// Defined in LayerUserData.h; please include that file instead.
121
class LayerUserData;
122
123
class DidCompositeObserver {
124
  public:
125
    virtual void DidComposite() = 0;
126
};
127
128
class FrameRecorder {
129
public:
130
  /**
131
   * Record (and return) frame-intervals and paint-times for frames which were presented
132
   *   between calling StartFrameTimeRecording and StopFrameTimeRecording.
133
   *
134
   * - Uses a cyclic buffer and serves concurrent consumers, so if Stop is called too late
135
   *     (elements were overwritten since Start), result is considered invalid and hence empty.
136
   * - Buffer is capable of holding 10 seconds @ 60fps (or more if frames were less frequent).
137
   *     Can be changed (up to 1 hour) via pref: toolkit.framesRecording.bufferSize.
138
   * - Note: the first frame-interval may be longer than expected because last frame
139
   *     might have been presented some time before calling StartFrameTimeRecording.
140
   */
141
142
  /**
143
   * Returns a handle which represents current recording start position.
144
   */
145
  virtual uint32_t StartFrameTimeRecording(int32_t aBufferSize);
146
147
  /**
148
   *  Clears, then populates aFrameIntervals with the recorded frame timing
149
   *  data. The array will be empty if data was overwritten since
150
   *  aStartIndex was obtained.
151
   */
152
  virtual void StopFrameTimeRecording(uint32_t         aStartIndex,
153
                                      nsTArray<float>& aFrameIntervals);
154
155
  void RecordFrame();
156
private:
157
  struct FramesTimingRecording
158
  {
159
    // Stores state and data for frame intervals and paint times recording.
160
    // see LayerManager::StartFrameTimeRecording() at Layers.cpp for more details.
161
    FramesTimingRecording()
162
      : mNextIndex(0)
163
      , mLatestStartIndex(0)
164
      , mCurrentRunStartIndex(0)
165
      , mIsPaused(true)
166
    {}
167
    nsTArray<float> mIntervals;
168
    TimeStamp mLastFrameTime;
169
    uint32_t mNextIndex;
170
    uint32_t mLatestStartIndex;
171
    uint32_t mCurrentRunStartIndex;
172
    bool mIsPaused;
173
  };
174
  FramesTimingRecording mRecording;
175
};
176
177
/*
178
 * Motivation: For truly smooth animation and video playback, we need to
179
 * be able to compose frames and render them on a dedicated thread (i.e.
180
 * off the main thread where DOM manipulation, script execution and layout
181
 * induce difficult-to-bound latency). This requires Gecko to construct
182
 * some kind of persistent scene structure (graph or tree) that can be
183
 * safely transmitted across threads. We have other scenarios (e.g. mobile
184
 * browsing) where retaining some rendered data between paints is desired
185
 * for performance, so again we need a retained scene structure.
186
 *
187
 * Our retained scene structure is a layer tree. Each layer represents
188
 * content which can be composited onto a destination surface; the root
189
 * layer is usually composited into a window, and non-root layers are
190
 * composited into their parent layers. Layers have attributes (e.g.
191
 * opacity and clipping) that influence their compositing.
192
 *
193
 * We want to support a variety of layer implementations, including
194
 * a simple "immediate mode" implementation that doesn't retain any
195
 * rendered data between paints (i.e. uses cairo in just the way that
196
 * Gecko used it before layers were introduced). But we also don't want
197
 * to have bifurcated "layers"/"non-layers" rendering paths in Gecko.
198
 * Therefore the layers API is carefully designed to permit maximally
199
 * efficient implementation in an "immediate mode" style. See the
200
 * BasicLayerManager for such an implementation.
201
 */
202
203
/**
204
 * A LayerManager controls a tree of layers. All layers in the tree
205
 * must use the same LayerManager.
206
 *
207
 * All modifications to a layer tree must happen inside a transaction.
208
 * Only the state of the layer tree at the end of a transaction is
209
 * rendered. Transactions cannot be nested
210
 *
211
 * Each transaction has two phases:
212
 * 1) Construction: layers are created, inserted, removed and have
213
 * properties set on them in this phase.
214
 * BeginTransaction and BeginTransactionWithTarget start a transaction in
215
 * the Construction phase.
216
 * 2) Drawing: PaintedLayers are rendered into in this phase, in tree
217
 * order. When the client has finished drawing into the PaintedLayers, it should
218
 * call EndTransaction to complete the transaction.
219
 *
220
 * All layer API calls happen on the main thread.
221
 *
222
 * Layers are refcounted. The layer manager holds a reference to the
223
 * root layer, and each container layer holds a reference to its children.
224
 */
225
class LayerManager : public FrameRecorder {
226
  NS_INLINE_DECL_REFCOUNTING(LayerManager)
227
228
protected:
229
  typedef mozilla::gfx::DrawTarget DrawTarget;
230
  typedef mozilla::gfx::IntSize IntSize;
231
  typedef mozilla::gfx::SurfaceFormat SurfaceFormat;
232
233
public:
234
  LayerManager()
235
    : mDestroyed(false)
236
    , mSnapEffectiveTransforms(true)
237
    , mId(0)
238
    , mInTransaction(false)
239
    , mPaintedPixelCount(0)
240
  {}
241
242
  /**
243
   * Release layers and resources held by this layer manager, and mark
244
   * it as destroyed.  Should do any cleanup necessary in preparation
245
   * for its widget going away.  After this call, only user data calls
246
   * are valid on the layer manager.
247
   */
248
  virtual void Destroy()
249
  {
250
    mDestroyed = true;
251
    mUserData.Destroy();
252
    mRoot = nullptr;
253
  }
254
  bool IsDestroyed() { return mDestroyed; }
255
256
  virtual ShadowLayerForwarder* AsShadowForwarder()
257
  { return nullptr; }
258
259
  virtual KnowsCompositor* AsKnowsCompositor()
260
  { return nullptr; }
261
262
  virtual LayerManagerComposite* AsLayerManagerComposite()
263
  { return nullptr; }
264
265
  virtual ClientLayerManager* AsClientLayerManager()
266
  { return nullptr; }
267
268
  virtual BasicLayerManager* AsBasicLayerManager()
269
  { return nullptr; }
270
  virtual HostLayerManager* AsHostLayerManager()
271
  { return nullptr; }
272
273
  virtual WebRenderLayerManager* AsWebRenderLayerManager()
274
  { return nullptr; }
275
276
  /**
277
   * Returns true if this LayerManager is owned by an nsIWidget,
278
   * and is used for drawing into the widget.
279
   */
280
  virtual bool IsWidgetLayerManager() { return true; }
281
  virtual bool IsInactiveLayerManager() { return false; }
282
283
  /**
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.
288
   */
289
  virtual bool BeginTransaction() = 0;
290
  /**
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.
296
   */
297
  virtual bool BeginTransactionWithTarget(gfxContext* aTarget) = 0;
298
299
  enum EndTransactionFlags {
300
    END_DEFAULT = 0,
301
    END_NO_IMMEDIATE_REDRAW = 1 << 0,  // Do not perform the drawing phase
302
    END_NO_COMPOSITE = 1 << 1, // Do not composite after drawing painted layer contents.
303
    END_NO_REMOTE_COMPOSITE = 1 << 2 // Do not schedule a composition with a remote Compositor, if one exists.
304
  };
305
306
  FrameLayerBuilder* GetLayerBuilder() {
307
    return reinterpret_cast<FrameLayerBuilder*>(GetUserData(&gLayerManagerLayerBuilder));
308
  }
309
310
  /**
311
   * Attempts to end an "empty transaction". There must have been no
312
   * changes to the layer tree since the BeginTransaction().
313
   * It's possible for this to fail; PaintedLayers may need to be updated
314
   * due to VRAM data being lost, for example. In such cases this method
315
   * returns false, and the caller must proceed with a normal layer tree
316
   * update and EndTransaction.
317
   */
318
  virtual bool EndEmptyTransaction(EndTransactionFlags aFlags = END_DEFAULT) = 0;
319
320
  /**
321
   * Function called to draw the contents of each PaintedLayer.
322
   * aRegionToDraw contains the region that needs to be drawn.
323
   * This would normally be a subregion of the visible region.
324
   * The callee must draw all of aRegionToDraw. Drawing outside
325
   * aRegionToDraw will be clipped out or ignored.
326
   * The callee must draw all of aRegionToDraw.
327
   * This region is relative to 0,0 in the PaintedLayer.
328
   *
329
   * aDirtyRegion should contain the total region that is be due to be painted
330
   * during the transaction, even though only aRegionToDraw should be drawn
331
   * during this call. aRegionToDraw must be entirely contained within
332
   * aDirtyRegion. If the total dirty region is unknown it is okay to pass a
333
   * subregion of the total dirty region, e.g. just aRegionToDraw, though it
334
   * may not be as efficient.
335
   *
336
   * aRegionToInvalidate contains a region whose contents have been
337
   * changed by the layer manager and which must therefore be invalidated.
338
   * For example, this could be non-empty if a retained layer internally
339
   * switches from RGBA to RGB or back ... we might want to repaint it to
340
   * consistently use subpixel-AA or not.
341
   * This region is relative to 0,0 in the PaintedLayer.
342
   * aRegionToInvalidate may contain areas that are outside
343
   * aRegionToDraw; the callee must ensure that these areas are repainted
344
   * in the current layer manager transaction or in a later layer
345
   * manager transaction.
346
   *
347
   * aContext must not be used after the call has returned.
348
   * We guarantee that buffered contents in the visible
349
   * region are valid once drawing is complete.
350
   *
351
   * The origin of aContext is 0,0 in the PaintedLayer.
352
   */
353
  typedef void (* DrawPaintedLayerCallback)(PaintedLayer* aLayer,
354
                                           gfxContext* aContext,
355
                                           const nsIntRegion& aRegionToDraw,
356
                                           const nsIntRegion& aDirtyRegion,
357
                                           DrawRegionClip aClip,
358
                                           const nsIntRegion& aRegionToInvalidate,
359
                                           void* aCallbackData);
360
361
  /**
362
   * Finish the construction phase of the transaction, perform the
363
   * drawing phase, and end the transaction.
364
   * During the drawing phase, all PaintedLayers in the tree are
365
   * drawn in tree order, exactly once each, except for those layers
366
   * where it is known that the visible region is empty.
367
   */
368
  virtual void EndTransaction(DrawPaintedLayerCallback aCallback,
369
                              void* aCallbackData,
370
                              EndTransactionFlags aFlags = END_DEFAULT) = 0;
371
372
  /**
373
   * Schedule a composition with the remote Compositor, if one exists
374
   * for this LayerManager. Useful in conjunction with the END_NO_REMOTE_COMPOSITE
375
   * flag to EndTransaction.
376
   */
377
  virtual void ScheduleComposite() {}
378
379
  virtual void SetNeedsComposite(bool aNeedsComposite) {}
380
  virtual bool NeedsComposite() const { return false; }
381
382
  virtual bool HasShadowManagerInternal() const { return false; }
383
  bool HasShadowManager() const { return HasShadowManagerInternal(); }
384
  virtual void StorePluginWidgetConfigurations(const nsTArray<nsIWidget::Configuration>& aConfigurations) {}
385
  bool IsSnappingEffectiveTransforms() { return mSnapEffectiveTransforms; }
386
387
  /**
388
   * Returns true if this LayerManager can properly support layers with
389
   * SurfaceMode::SURFACE_COMPONENT_ALPHA. LayerManagers that can't will use
390
   * transparent surfaces (and lose subpixel-AA for text).
391
   */
392
  virtual bool AreComponentAlphaLayersEnabled();
393
394
  /**
395
   * Returns true if this LayerManager always requires an intermediate surface
396
   * to render blend operations.
397
   */
398
  virtual bool BlendingRequiresIntermediateSurface() { return false; }
399
400
  /**
401
   * CONSTRUCTION PHASE ONLY
402
   * Set the root layer. The root layer is initially null. If there is
403
   * no root layer, EndTransaction won't draw anything.
404
   */
405
  virtual void SetRoot(Layer* aLayer) = 0;
406
  /**
407
   * Can be called anytime
408
   */
409
  Layer* GetRoot() { return mRoot; }
410
411
  /**
412
   * Does a breadth-first search from the root layer to find the first
413
   * scrollable layer, and returns its ViewID. Note that there may be
414
   * other layers in the tree which share the same ViewID.
415
   * Can be called any time.
416
   */
417
  FrameMetrics::ViewID GetRootScrollableLayerId();
418
419
  /**
420
   * Returns a LayerMetricsWrapper containing the Root
421
   * Content Documents layer.
422
   */
423
  LayerMetricsWrapper GetRootContentLayer();
424
425
  /**
426
   * CONSTRUCTION PHASE ONLY
427
   * Called when a managee has mutated.
428
   * Subclasses overriding this method must first call their
429
   * superclass's impl
430
   */
431
  virtual void Mutated(Layer* aLayer) { }
432
  virtual void MutatedSimple(Layer* aLayer) { }
433
434
  /**
435
   * Hints that can be used during PaintedLayer creation to influence the type
436
   * or properties of the layer created.
437
   *
438
   * NONE: No hint.
439
   * SCROLLABLE: This layer may represent scrollable content.
440
   */
441
  enum PaintedLayerCreationHint {
442
    NONE, SCROLLABLE
443
  };
444
445
  /**
446
   * CONSTRUCTION PHASE ONLY
447
   * Create a PaintedLayer for this manager's layer tree.
448
   */
449
  virtual already_AddRefed<PaintedLayer> CreatePaintedLayer() = 0;
450
  /**
451
   * CONSTRUCTION PHASE ONLY
452
   * Create a PaintedLayer for this manager's layer tree, with a creation hint
453
   * parameter to help optimise the type of layer created.
454
   */
455
  virtual already_AddRefed<PaintedLayer> CreatePaintedLayerWithHint(PaintedLayerCreationHint) {
456
    return CreatePaintedLayer();
457
  }
458
  /**
459
   * CONSTRUCTION PHASE ONLY
460
   * Create a ContainerLayer for this manager's layer tree.
461
   */
462
  virtual already_AddRefed<ContainerLayer> CreateContainerLayer() = 0;
463
  /**
464
   * CONSTRUCTION PHASE ONLY
465
   * Create an ImageLayer for this manager's layer tree.
466
   */
467
  virtual already_AddRefed<ImageLayer> CreateImageLayer() = 0;
468
  /**
469
   * CONSTRUCTION PHASE ONLY
470
   * Create a ColorLayer for this manager's layer tree.
471
   */
472
  virtual already_AddRefed<ColorLayer> CreateColorLayer() = 0;
473
  /**
474
   * CONSTRUCTION PHASE ONLY
475
   * Create a CanvasLayer for this manager's layer tree.
476
   */
477
  virtual already_AddRefed<CanvasLayer> CreateCanvasLayer() = 0;
478
  /**
479
   * CONSTRUCTION PHASE ONLY
480
   * Create a ReadbackLayer for this manager's layer tree.
481
   */
482
  virtual already_AddRefed<ReadbackLayer> CreateReadbackLayer() { return nullptr; }
483
  /**
484
   * CONSTRUCTION PHASE ONLY
485
   * Create a RefLayer for this manager's layer tree.
486
   */
487
  virtual already_AddRefed<RefLayer> CreateRefLayer() { return nullptr; }
488
  /**
489
   * Can be called anytime, from any thread.
490
   *
491
   * Creates an Image container which forwards its images to the compositor within
492
   * layer transactions on the main thread or asynchronously using the ImageBridge IPDL protocol.
493
   * In the case of asynchronous, If the protocol is not available, the returned ImageContainer
494
   * will forward images within layer transactions.
495
   */
496
  static already_AddRefed<ImageContainer> CreateImageContainer(ImageContainer::Mode flag
497
                                                                = ImageContainer::SYNCHRONOUS);
498
499
  /**
500
   * Type of layer manager his is. This is to be used sparsely in order to
501
   * avoid a lot of Layers backend specific code. It should be used only when
502
   * Layers backend specific functionality is necessary.
503
   */
504
  virtual LayersBackend GetBackendType() = 0;
505
506
  /**
507
   * Type of layers backend that will be used to composite this layer tree.
508
   * When compositing is done remotely, then this returns the layers type
509
   * of the compositor.
510
   */
511
  virtual LayersBackend GetCompositorBackendType() { return GetBackendType(); }
512
513
  /**
514
   * Creates a DrawTarget which is optimized for inter-operating with this
515
   * layer manager.
516
   */
517
  virtual already_AddRefed<DrawTarget>
518
    CreateOptimalDrawTarget(const IntSize &aSize,
519
                            SurfaceFormat imageFormat);
520
521
  /**
522
   * Creates a DrawTarget for alpha masks which is optimized for inter-
523
   * operating with this layer manager. In contrast to CreateOptimalDrawTarget,
524
   * this surface is optimised for drawing alpha only and we assume that
525
   * drawing the mask is fairly simple.
526
   */
527
  virtual already_AddRefed<DrawTarget>
528
    CreateOptimalMaskDrawTarget(const IntSize &aSize);
529
530
  /**
531
   * Creates a DrawTarget for use with canvas which is optimized for
532
   * inter-operating with this layermanager.
533
   */
534
  virtual already_AddRefed<mozilla::gfx::DrawTarget>
535
    CreateDrawTarget(const mozilla::gfx::IntSize &aSize,
536
                     mozilla::gfx::SurfaceFormat aFormat);
537
538
  /**
539
   * Creates a PersistentBufferProvider for use with canvas which is optimized for
540
   * inter-operating with this layermanager.
541
   */
542
  virtual already_AddRefed<PersistentBufferProvider>
543
    CreatePersistentBufferProvider(const mozilla::gfx::IntSize &aSize,
544
                                   mozilla::gfx::SurfaceFormat aFormat);
545
546
  virtual bool CanUseCanvasLayerForSize(const gfx::IntSize &aSize) { return true; }
547
548
  /**
549
   * returns the maximum texture size on this layer backend, or INT32_MAX
550
   * if there is no maximum
551
   */
552
  virtual int32_t GetMaxTextureSize() const = 0;
553
554
  /**
555
   * Return the name of the layer manager's backend.
556
   */
557
  virtual void GetBackendName(nsAString& aName) = 0;
558
559
  /**
560
   * This setter can be used anytime. The user data for all keys is
561
   * initially null. Ownership pases to the layer manager.
562
   */
563
  void SetUserData(void* aKey, LayerUserData* aData)
564
  {
565
    mUserData.Add(static_cast<gfx::UserDataKey*>(aKey), aData, LayerUserDataDestroy);
566
  }
567
  /**
568
   * This can be used anytime. Ownership passes to the caller!
569
   */
570
  UniquePtr<LayerUserData> RemoveUserData(void* aKey);
571
572
  /**
573
   * This getter can be used anytime.
574
   */
575
  bool HasUserData(void* aKey)
576
  {
577
    return mUserData.Has(static_cast<gfx::UserDataKey*>(aKey));
578
  }
579
  /**
580
   * This getter can be used anytime. Ownership is retained by the layer
581
   * manager.
582
   */
583
  LayerUserData* GetUserData(void* aKey) const
584
  {
585
    return static_cast<LayerUserData*>(mUserData.Get(static_cast<gfx::UserDataKey*>(aKey)));
586
  }
587
588
  /**
589
   * Must be called outside of a layers transaction.
590
   *
591
   * For the subtree rooted at |aSubtree|, this attempts to free up
592
   * any free-able resources like retained buffers, but may do nothing
593
   * at all.  After this call, the layer tree is left in an undefined
594
   * state; the layers in |aSubtree|'s subtree may no longer have
595
   * buffers with valid content and may no longer be able to draw
596
   * their visible and valid regions.
597
   *
598
   * In general, a painting or forwarding transaction on |this| must
599
   * complete on the tree before it returns to a valid state.
600
   *
601
   * Resource freeing begins from |aSubtree| or |mRoot| if |aSubtree|
602
   * is null.  |aSubtree|'s manager must be this.
603
   */
604
  virtual void ClearCachedResources(Layer* aSubtree = nullptr) {}
605
606
  /**
607
   * Flag the next paint as the first for a document.
608
   */
609
  virtual void SetIsFirstPaint() {}
610
611
  /**
612
   * Set the current focus target to be sent with the next paint.
613
   */
614
  virtual void SetFocusTarget(const FocusTarget& aFocusTarget) {}
615
616
  /**
617
   * Make sure that the previous transaction has been entirely
618
   * completed.
619
   *
620
   * Note: This may sychronously wait on a remote compositor
621
   * to complete rendering.
622
   */
623
  virtual void FlushRendering() { }
624
625
  /**
626
   * Make sure that the previous transaction has been
627
   * received. This will synchronsly wait on a remote compositor. */
628
  virtual void WaitOnTransactionProcessed() { }
629
630
  virtual void SendInvalidRegion(const nsIntRegion& aRegion) {}
631
632
  /**
633
   * Checks if we need to invalidate the OS widget to trigger
634
   * painting when updating this layer manager.
635
   */
636
  virtual bool NeedsWidgetInvalidation() { return true; }
637
638
  virtual const char* Name() const { return "???"; }
639
640
  /**
641
   * Dump information about this layer manager and its managed tree to
642
   * aStream.
643
   */
644
  void Dump(std::stringstream& aStream, const char* aPrefix="",
645
            bool aDumpHtml=false, bool aSorted=false);
646
  /**
647
   * Dump information about just this layer manager itself to aStream
648
   */
649
  void DumpSelf(std::stringstream& aStream, const char* aPrefix="", bool aSorted=false);
650
  void Dump(bool aSorted=false);
651
652
  /**
653
   * Dump information about this layer manager and its managed tree to
654
   * layerscope packet.
655
   */
656
  void Dump(layerscope::LayersPacket* aPacket);
657
658
  /**
659
   * Log information about this layer manager and its managed tree to
660
   * the NSPR log (if enabled for "Layers").
661
   */
662
  void Log(const char* aPrefix="");
663
  /**
664
   * Log information about just this layer manager itself to the NSPR
665
   * log (if enabled for "Layers").
666
   */
667
  void LogSelf(const char* aPrefix="");
668
669
  static bool IsLogEnabled();
670
  static mozilla::LogModule* GetLog();
671
672
  bool IsCompositingCheap(LayersBackend aBackend)
673
  {
674
    // LayersBackend::LAYERS_NONE is an error state, but in that case we should try to
675
    // avoid loading the compositor!
676
    return LayersBackend::LAYERS_BASIC != aBackend && LayersBackend::LAYERS_NONE != aBackend;
677
  }
678
679
  virtual bool IsCompositingCheap() { return true; }
680
681
  bool IsInTransaction() const { return mInTransaction; }
682
  virtual void GetFrameUniformity(FrameUniformityData* aOutData) { }
683
684
  virtual void SetRegionToClear(const nsIntRegion& aRegion)
685
  {
686
    mRegionToClear = aRegion;
687
  }
688
689
  virtual float RequestProperty(const nsAString& property) { return -1; }
690
691
  const TimeStamp& GetAnimationReadyTime() const {
692
    return mAnimationReadyTime;
693
  }
694
695
  virtual bool AsyncPanZoomEnabled() const {
696
    return false;
697
  }
698
699
  static void LayerUserDataDestroy(void* data);
700
701
  void AddPaintedPixelCount(int32_t aCount) {
702
    mPaintedPixelCount += aCount;
703
  }
704
705
  uint32_t GetAndClearPaintedPixelCount() {
706
    uint32_t count = mPaintedPixelCount;
707
    mPaintedPixelCount = 0;
708
    return count;
709
  }
710
711
  virtual void SetLayersObserverEpoch(LayersObserverEpoch aEpoch) {}
712
713
  virtual void DidComposite(TransactionId aTransactionId,
714
                            const mozilla::TimeStamp& aCompositeStart,
715
                            const mozilla::TimeStamp& aCompositeEnd) {}
716
717
  virtual void AddDidCompositeObserver(DidCompositeObserver* aObserver) { MOZ_CRASH("GFX: LayerManager"); }
718
  virtual void RemoveDidCompositeObserver(DidCompositeObserver* aObserver) { MOZ_CRASH("GFX: LayerManager"); }
719
720
  virtual void UpdateTextureFactoryIdentifier(const TextureFactoryIdentifier& aNewIdentifier) {}
721
722
  virtual TextureFactoryIdentifier GetTextureFactoryIdentifier()
723
  {
724
    return TextureFactoryIdentifier();
725
  }
726
727
  virtual void SetTransactionIdAllocator(TransactionIdAllocator* aAllocator) {}
728
729
  virtual TransactionId GetLastTransactionId() { return TransactionId{0}; }
730
731
  virtual CompositorBridgeChild* GetCompositorBridgeChild() { return nullptr; }
732
733
protected:
734
  RefPtr<Layer> mRoot;
735
  gfx::UserData mUserData;
736
  bool mDestroyed;
737
  bool mSnapEffectiveTransforms;
738
739
  nsIntRegion mRegionToClear;
740
741
  // Protected destructor, to discourage deletion outside of Release():
742
  virtual ~LayerManager() {}
743
744
  // Print interesting information about this into aStreamo.  Internally
745
  // used to implement Dump*() and Log*().
746
  virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix);
747
748
  // Print interesting information about this into layerscope packet.
749
  // Internally used to implement Dump().
750
  virtual void DumpPacket(layerscope::LayersPacket* aPacket);
751
752
  uint64_t mId;
753
  bool mInTransaction;
754
  // The time when painting most recently finished. This is recorded so that
755
  // we can time any play-pending animations from this point.
756
  TimeStamp mAnimationReadyTime;
757
  // The count of pixels that were painted in the current transaction.
758
  uint32_t mPaintedPixelCount;
759
760
public:
761
  /*
762
   * Methods to store/get/clear a "pending scroll info update" object on a
763
   * per-scrollid basis. This is used for empty transactions that push over
764
   * scroll position updates to the APZ code.
765
   */
766
  virtual bool SetPendingScrollUpdateForNextTransaction(FrameMetrics::ViewID aScrollId,
767
                                                        const ScrollUpdateInfo& aUpdateInfo);
768
  Maybe<ScrollUpdateInfo> GetPendingScrollInfoUpdate(FrameMetrics::ViewID aScrollId);
769
  void ClearPendingScrollInfoUpdate();
770
protected:
771
  ScrollUpdatesMap mPendingScrollUpdates;
772
};
773
774
/**
775
 * A Layer represents anything that can be rendered onto a destination
776
 * surface.
777
 */
778
class Layer {
779
  NS_INLINE_DECL_REFCOUNTING(Layer)
780
781
  typedef InfallibleTArray<Animation> AnimationArray;
782
783
public:
784
  // Keep these in alphabetical order
785
  enum LayerType {
786
    TYPE_CANVAS,
787
    TYPE_COLOR,
788
    TYPE_CONTAINER,
789
    TYPE_DISPLAYITEM,
790
    TYPE_IMAGE,
791
    TYPE_READBACK,
792
    TYPE_REF,
793
    TYPE_SHADOW,
794
    TYPE_PAINTED
795
  };
796
797
  /**
798
   * Returns the LayerManager this Layer belongs to. Note that the layer
799
   * manager might be in a destroyed state, at which point it's only
800
   * valid to set/get user data from it.
801
   */
802
0
  LayerManager* Manager() { return mManager; }
803
804
  /**
805
   * This should only be called when changing layer managers from HostLayers.
806
   */
807
  void SetManager(LayerManager* aManager, HostLayer* aSelf);
808
809
  enum {
810
    /**
811
     * If this is set, the caller is promising that by the end of this
812
     * transaction the entire visible region (as specified by
813
     * SetVisibleRegion) will be filled with opaque content.
814
     */
815
    CONTENT_OPAQUE = 0x01,
816
    /**
817
     * If this is set, the caller is notifying that the contents of this layer
818
     * require per-component alpha for optimal fidelity. However, there is no
819
     * guarantee that component alpha will be supported for this layer at
820
     * paint time.
821
     * This should never be set at the same time as CONTENT_OPAQUE.
822
     */
823
    CONTENT_COMPONENT_ALPHA = 0x02,
824
825
    /**
826
     * If this is set then one of the descendant layers of this one has
827
     * CONTENT_COMPONENT_ALPHA set.
828
     */
829
    CONTENT_COMPONENT_ALPHA_DESCENDANT = 0x04,
830
831
    /**
832
     * If this is set then this layer is part of a preserve-3d group, and should
833
     * be sorted with sibling layers that are also part of the same group.
834
     */
835
    CONTENT_EXTEND_3D_CONTEXT = 0x08,
836
    /**
837
     * This indicates that the transform may be changed on during an empty
838
     * transaction where there is no possibility of redrawing the content, so the
839
     * implementation should be ready for that.
840
     */
841
    CONTENT_MAY_CHANGE_TRANSFORM = 0x10,
842
843
    /**
844
     * Disable subpixel AA for this layer. This is used if the display isn't suited
845
     * for subpixel AA like hidpi or rotated content.
846
     */
847
    CONTENT_DISABLE_SUBPIXEL_AA = 0x20,
848
849
    /**
850
     * If this is set then the layer contains content that may look objectionable
851
     * if not handled as an active layer (such as text with an animated transform).
852
     * This is for internal layout/FrameLayerBuilder usage only until flattening
853
     * code is obsoleted. See bug 633097
854
     */
855
    CONTENT_DISABLE_FLATTENING = 0x40,
856
857
    /**
858
     * This layer is hidden if the backface of the layer is visible
859
     * to user.
860
     */
861
    CONTENT_BACKFACE_HIDDEN = 0x80
862
  };
863
  /**
864
   * CONSTRUCTION PHASE ONLY
865
   * This lets layout make some promises about what will be drawn into the
866
   * visible region of the PaintedLayer. This enables internal quality
867
   * and performance optimizations.
868
   */
869
  void SetContentFlags(uint32_t aFlags)
870
  {
871
    NS_ASSERTION((aFlags & (CONTENT_OPAQUE | CONTENT_COMPONENT_ALPHA)) !=
872
                 (CONTENT_OPAQUE | CONTENT_COMPONENT_ALPHA),
873
                 "Can't be opaque and require component alpha");
874
    if (mSimpleAttrs.SetContentFlags(aFlags)) {
875
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ContentFlags", this));
876
      MutatedSimple();
877
    }
878
  }
879
880
  /**
881
   * CONSTRUCTION PHASE ONLY
882
   * Tell this layer which region will be visible. The visible region
883
   * is a region which contains all the contents of the layer that can
884
   * actually affect the rendering of the window. It can exclude areas
885
   * that are covered by opaque contents of other layers, and it can
886
   * exclude areas where this layer simply contains no content at all.
887
   * (This can be an overapproximation to the "true" visible region.)
888
   *
889
   * There is no general guarantee that drawing outside the bounds of the
890
   * visible region will be ignored. So if a layer draws outside the bounds
891
   * of its visible region, it needs to ensure that what it draws is valid.
892
   */
893
  virtual void SetVisibleRegion(const LayerIntRegion& aRegion)
894
0
  {
895
0
    // IsEmpty is required otherwise we get invalidation glitches.
896
0
    // See bug 1288464 for investigating why.
897
0
    if (!mVisibleRegion.IsEqual(aRegion) || aRegion.IsEmpty()) {
898
0
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) VisibleRegion was %s is %s", this,
899
0
        mVisibleRegion.ToString().get(), aRegion.ToString().get()));
900
0
      mVisibleRegion = aRegion;
901
0
      Mutated();
902
0
    }
903
0
  }
904
905
  /**
906
   * CONSTRUCTION PHASE ONLY
907
   * Set the (sub)document metrics used to render the Layer subtree
908
   * rooted at this. Note that a layer may have multiple FrameMetrics
909
   * objects; calling this function will remove all of them and replace
910
   * them with the provided FrameMetrics. See the documentation for
911
   * SetFrameMetrics(const nsTArray<FrameMetrics>&) for more details.
912
   */
913
  void SetScrollMetadata(const ScrollMetadata& aScrollMetadata)
914
  {
915
    Manager()->ClearPendingScrollInfoUpdate();
916
    if (mScrollMetadata.Length() != 1 || mScrollMetadata[0] != aScrollMetadata) {
917
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) FrameMetrics", this));
918
      mScrollMetadata.ReplaceElementsAt(0, mScrollMetadata.Length(), aScrollMetadata);
919
      ScrollMetadataChanged();
920
      Mutated();
921
    }
922
  }
923
924
  /**
925
   * CONSTRUCTION PHASE ONLY
926
   * Set the (sub)document metrics used to render the Layer subtree
927
   * rooted at this. There might be multiple metrics on this layer
928
   * because the layer may, for example, be contained inside multiple
929
   * nested scrolling subdocuments. In general a Layer having multiple
930
   * ScrollMetadata objects is conceptually equivalent to having a stack
931
   * of ContainerLayers that have been flattened into this Layer.
932
   * See the documentation in LayerMetricsWrapper.h for a more detailed
933
   * explanation of this conceptual equivalence.
934
   *
935
   * Note also that there is actually a many-to-many relationship between
936
   * Layers and ScrollMetadata, because multiple Layers may have identical
937
   * ScrollMetadata objects. This happens when those layers belong to the
938
   * same scrolling subdocument and therefore end up with the same async
939
   * transform when they are scrolled by the APZ code.
940
   */
941
  void SetScrollMetadata(const nsTArray<ScrollMetadata>& aMetadataArray)
942
  {
943
    Manager()->ClearPendingScrollInfoUpdate();
944
    if (mScrollMetadata != aMetadataArray) {
945
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) FrameMetrics", this));
946
      mScrollMetadata = aMetadataArray;
947
      ScrollMetadataChanged();
948
      Mutated();
949
    }
950
  }
951
952
  /*
953
   * Compositor event handling
954
   * =========================
955
   * When a touch-start event (or similar) is sent to the AsyncPanZoomController,
956
   * it needs to decide whether the event should be sent to the main thread.
957
   * Each layer has a list of event handling regions. When the compositor needs
958
   * to determine how to handle a touch event, it scans the layer tree from top
959
   * to bottom in z-order (traversing children before their parents). Points
960
   * outside the clip region for a layer cause that layer (and its subtree)
961
   * to be ignored. If a layer has a mask layer, and that mask layer's alpha
962
   * value is zero at the event point, then the layer and its subtree should
963
   * be ignored.
964
   * For each layer, if the point is outside its hit region, we ignore the layer
965
   * and move onto the next. If the point is inside its hit region but
966
   * outside the dispatch-to-content region, we can initiate a gesture without
967
   * consulting the content thread. Otherwise we must dispatch the event to
968
   * content.
969
   * Note that if a layer or any ancestor layer has a ForceEmptyHitRegion
970
   * override in GetEventRegionsOverride() then the hit-region must be treated
971
   * as empty. Similarly, if there is a ForceDispatchToContent override then
972
   * the dispatch-to-content region must be treated as encompassing the entire
973
   * hit region, and therefore we must consult the content thread before
974
   * initiating a gesture. (If both flags are set, ForceEmptyHitRegion takes
975
   * priority.)
976
   */
977
  /**
978
   * CONSTRUCTION PHASE ONLY
979
   * Set the event handling region.
980
   */
981
  void SetEventRegions(const EventRegions& aRegions)
982
  {
983
    if (mEventRegions != aRegions) {
984
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) eventregions were %s, now %s", this,
985
        mEventRegions.ToString().get(), aRegions.ToString().get()));
986
      mEventRegions = aRegions;
987
      Mutated();
988
    }
989
  }
990
991
  /**
992
   * CONSTRUCTION PHASE ONLY
993
   * Set the opacity which will be applied to this layer as it
994
   * is composited to the destination.
995
   */
996
  void SetOpacity(float aOpacity)
997
  {
998
    if (mSimpleAttrs.SetOpacity(aOpacity)) {
999
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) Opacity", this));
1000
      MutatedSimple();
1001
    }
1002
  }
1003
1004
  void SetMixBlendMode(gfx::CompositionOp aMixBlendMode)
1005
  {
1006
    if (mSimpleAttrs.SetMixBlendMode(aMixBlendMode)) {
1007
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) MixBlendMode", this));
1008
      MutatedSimple();
1009
    }
1010
  }
1011
1012
  void SetForceIsolatedGroup(bool aForceIsolatedGroup)
1013
  {
1014
    if (mSimpleAttrs.SetForceIsolatedGroup(aForceIsolatedGroup)) {
1015
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ForceIsolatedGroup", this));
1016
      MutatedSimple();
1017
    }
1018
  }
1019
1020
  bool GetForceIsolatedGroup() const
1021
  {
1022
    return mSimpleAttrs.GetForceIsolatedGroup();
1023
  }
1024
1025
  /**
1026
   * CONSTRUCTION PHASE ONLY
1027
   * Set a clip rect which will be applied to this layer as it is
1028
   * composited to the destination. The coordinates are relative to
1029
   * the parent layer (i.e. the contents of this layer
1030
   * are transformed before this clip rect is applied).
1031
   * For the root layer, the coordinates are relative to the widget,
1032
   * in device pixels.
1033
   * If aRect is null no clipping will be performed.
1034
   */
1035
  void SetClipRect(const Maybe<ParentLayerIntRect>& aRect)
1036
  {
1037
    if (mClipRect) {
1038
      if (!aRect) {
1039
        MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ClipRect was %d,%d,%d,%d is <none>", this,
1040
                                            mClipRect->X(), mClipRect->Y(), mClipRect->Width(), mClipRect->Height()));
1041
        mClipRect.reset();
1042
        Mutated();
1043
      } else {
1044
        if (!aRect->IsEqualEdges(*mClipRect)) {
1045
          MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ClipRect was %d,%d,%d,%d is %d,%d,%d,%d", this,
1046
                                              mClipRect->X(), mClipRect->Y(), mClipRect->Width(), mClipRect->Height(),
1047
                                              aRect->X(), aRect->Y(), aRect->Width(), aRect->Height()));
1048
          mClipRect = aRect;
1049
          Mutated();
1050
        }
1051
      }
1052
    } else {
1053
      if (aRect) {
1054
        MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ClipRect was <none> is %d,%d,%d,%d", this,
1055
                                            aRect->X(), aRect->Y(), aRect->Width(), aRect->Height()));
1056
        mClipRect = aRect;
1057
        Mutated();
1058
      }
1059
    }
1060
  }
1061
1062
  /**
1063
   * CONSTRUCTION PHASE ONLY
1064
   * Set an optional scrolled clip on the layer.
1065
   * The scrolled clip, if present, consists of a clip rect and an optional mask.
1066
   * This scrolled clip is always scrolled by all scroll frames associated with
1067
   * this layer. (By contrast, the scroll clips stored in ScrollMetadata are
1068
   * only scrolled by scroll frames above that ScrollMetadata, and the layer's
1069
   * mClipRect is always fixed to the layer contents (which may or may not be
1070
   * scrolled by some of the scroll frames associated with the layer, depending
1071
   * on whether the layer is fixed).)
1072
   */
1073
  void SetScrolledClip(const Maybe<LayerClip>& aScrolledClip)
1074
  {
1075
    if (mSimpleAttrs.SetScrolledClip(aScrolledClip)) {
1076
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ScrolledClip", this));
1077
      MutatedSimple();
1078
    }
1079
  }
1080
1081
  /**
1082
   * CONSTRUCTION PHASE ONLY
1083
   * Set a layer to mask this layer.
1084
   *
1085
   * The mask layer should be applied using its effective transform (after it
1086
   * is calculated by ComputeEffectiveTransformForMaskLayer), this should use
1087
   * this layer's parent's transform and the mask layer's transform, but not
1088
   * this layer's. That is, the mask layer is specified relative to this layer's
1089
   * position in it's parent layer's coord space.
1090
   * Currently, only 2D translations are supported for the mask layer transform.
1091
   *
1092
   * Ownership of aMaskLayer passes to this.
1093
   * Typical use would be an ImageLayer with an alpha image used for masking.
1094
   * See also ContainerState::BuildMaskLayer in FrameLayerBuilder.cpp.
1095
   */
1096
  void SetMaskLayer(Layer* aMaskLayer)
1097
  {
1098
#ifdef DEBUG
1099
    if (aMaskLayer) {
1100
      bool maskIs2D = aMaskLayer->GetTransform().CanDraw2D();
1101
      NS_ASSERTION(maskIs2D, "Mask layer has invalid transform.");
1102
    }
1103
#endif
1104
1105
    if (mMaskLayer != aMaskLayer) {
1106
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) MaskLayer", this));
1107
      mMaskLayer = aMaskLayer;
1108
      Mutated();
1109
    }
1110
  }
1111
1112
  /**
1113
   * CONSTRUCTION PHASE ONLY
1114
   * Add mask layers associated with LayerClips.
1115
   */
1116
  void SetAncestorMaskLayers(const nsTArray<RefPtr<Layer>>& aLayers) {
1117
    if (aLayers != mAncestorMaskLayers) {
1118
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) AncestorMaskLayers", this));
1119
      mAncestorMaskLayers = aLayers;
1120
      Mutated();
1121
    }
1122
  }
1123
1124
  /**
1125
   * CONSTRUCTION PHASE ONLY
1126
   * Add a mask layer associated with a LayerClip.
1127
   */
1128
  void AddAncestorMaskLayer(const RefPtr<Layer>& aLayer) {
1129
    mAncestorMaskLayers.AppendElement(aLayer);
1130
    Mutated();
1131
  }
1132
1133
  /**
1134
   * CONSTRUCTION PHASE ONLY
1135
   * Tell this layer what its transform should be. The transformation
1136
   * is applied when compositing the layer into its parent container.
1137
   */
1138
  void SetBaseTransform(const gfx::Matrix4x4& aMatrix)
1139
  {
1140
    NS_ASSERTION(!aMatrix.IsSingular(),
1141
                 "Shouldn't be trying to draw with a singular matrix!");
1142
    mPendingTransform = nullptr;
1143
    if (!mSimpleAttrs.SetTransform(aMatrix)) {
1144
      return;
1145
    }
1146
    MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) BaseTransform", this));
1147
    MutatedSimple();
1148
  }
1149
1150
  /**
1151
   * Can be called at any time.
1152
   *
1153
   * Like SetBaseTransform(), but can be called before the next
1154
   * transform (i.e. outside an open transaction).  Semantically, this
1155
   * method enqueues a new transform value to be set immediately after
1156
   * the next transaction is opened.
1157
   */
1158
  void SetBaseTransformForNextTransaction(const gfx::Matrix4x4& aMatrix)
1159
  {
1160
    mPendingTransform = new gfx::Matrix4x4(aMatrix);
1161
  }
1162
1163
  void SetPostScale(float aXScale, float aYScale)
1164
  {
1165
    if (!mSimpleAttrs.SetPostScale(aXScale, aYScale)) {
1166
      return;
1167
    }
1168
    MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) PostScale", this));
1169
    MutatedSimple();
1170
  }
1171
1172
  /**
1173
   * CONSTRUCTION PHASE ONLY
1174
   * A layer is "fixed position" when it draws content from a content
1175
   * (not chrome) document, the topmost content document has a root scrollframe
1176
   * with a displayport, but the layer does not move when that displayport scrolls.
1177
   */
1178
  void SetIsFixedPosition(bool aFixedPosition)
1179
  {
1180
    if (mSimpleAttrs.SetIsFixedPosition(aFixedPosition)) {
1181
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) IsFixedPosition", this));
1182
      MutatedSimple();
1183
    }
1184
  }
1185
1186
  /**
1187
   * CONSTRUCTION PHASE ONLY
1188
   * This flag is true when the transform on the layer is a perspective
1189
   * transform. The compositor treats perspective transforms specially
1190
   * for async scrolling purposes.
1191
   */
1192
  void SetTransformIsPerspective(bool aTransformIsPerspective)
1193
  {
1194
    if (mSimpleAttrs.SetTransformIsPerspective(aTransformIsPerspective)) {
1195
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) TransformIsPerspective", this));
1196
      MutatedSimple();
1197
    }
1198
  }
1199
  // This is only called when the layer tree is updated. Do not call this from
1200
  // layout code.  To add an animation to this layer, use AddAnimation.
1201
  void SetCompositorAnimations(const CompositorAnimations& aCompositorAnimations);
1202
  // Go through all animations in this layer and its children and, for
1203
  // any animations with a null start time, update their start time such
1204
  // that at |aReadyTime| the animation's current time corresponds to its
1205
  // 'initial current time' value.
1206
  void StartPendingAnimations(const TimeStamp& aReadyTime);
1207
1208
  void ClearCompositorAnimations();
1209
1210
  /**
1211
   * CONSTRUCTION PHASE ONLY
1212
   * If a layer represents a fixed position element, this data is stored on the
1213
   * layer for use by the compositor.
1214
   *
1215
   *   - |aScrollId| identifies the scroll frame that this element is fixed
1216
   *     with respect to.
1217
   *
1218
   *   - |aAnchor| is the point on the layer that is considered the "anchor"
1219
   *     point, that is, the point which remains in the same position when
1220
   *     compositing the layer tree with a transformation (such as when
1221
   *     asynchronously scrolling and zooming).
1222
   *
1223
   *   - |aSides| is the set of sides to which the element is fixed relative to.
1224
   *     This is used if the viewport size is changed in the compositor and
1225
   *     fixed position items need to shift accordingly. This value is made up
1226
   *     combining appropriate values from mozilla::SideBits.
1227
   */
1228
  void SetFixedPositionData(FrameMetrics::ViewID aScrollId,
1229
                            const LayerPoint& aAnchor,
1230
                            int32_t aSides)
1231
  {
1232
    if (mSimpleAttrs.SetFixedPositionData(aScrollId, aAnchor, aSides)) {
1233
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) FixedPositionData", this));
1234
      MutatedSimple();
1235
    }
1236
  }
1237
1238
  /**
1239
   * CONSTRUCTION PHASE ONLY
1240
   * If a layer is "sticky position", |aScrollId| holds the scroll identifier
1241
   * of the scrollable content that contains it. The difference between the two
1242
   * rectangles |aOuter| and |aInner| is treated as two intervals in each
1243
   * dimension, with the current scroll position at the origin. For each
1244
   * dimension, while that component of the scroll position lies within either
1245
   * interval, the layer should not move relative to its scrolling container.
1246
   */
1247
  void SetStickyPositionData(FrameMetrics::ViewID aScrollId,
1248
                             LayerRectAbsolute aOuter, LayerRectAbsolute aInner)
1249
  {
1250
    if (mSimpleAttrs.SetStickyPositionData(aScrollId, aOuter, aInner)) {
1251
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) StickyPositionData", this));
1252
      MutatedSimple();
1253
    }
1254
  }
1255
1256
  /**
1257
   * CONSTRUCTION PHASE ONLY
1258
   * If a layer is a scroll thumb container layer or a scrollbar container
1259
   * layer, set the scroll identifier of the scroll frame scrolled by
1260
   * the scrollbar, and other data related to the scrollbar.
1261
   */
1262
  void SetScrollbarData(const ScrollbarData& aThumbData)
1263
  {
1264
    if (mSimpleAttrs.SetScrollbarData(aThumbData)) {
1265
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ScrollbarData", this));
1266
      MutatedSimple();
1267
    }
1268
  }
1269
1270
  // Used when forwarding transactions. Do not use at any other time.
1271
  void SetSimpleAttributes(const SimpleLayerAttributes& aAttrs) {
1272
    mSimpleAttrs = aAttrs;
1273
  }
1274
  const SimpleLayerAttributes& GetSimpleAttributes() const {
1275
    return mSimpleAttrs;
1276
  }
1277
1278
  // These getters can be used anytime.
1279
  float GetOpacity() { return mSimpleAttrs.GetOpacity(); }
1280
0
  gfx::CompositionOp GetMixBlendMode() const { return mSimpleAttrs.GetMixBlendMode(); }
1281
  const Maybe<ParentLayerIntRect>& GetClipRect() const { return mClipRect; }
1282
  const Maybe<LayerClip>& GetScrolledClip() const { return mSimpleAttrs.GetScrolledClip(); }
1283
  Maybe<ParentLayerIntRect> GetScrolledClipRect() const;
1284
0
  uint32_t GetContentFlags() { return mSimpleAttrs.GetContentFlags(); }
1285
  const LayerIntRegion& GetVisibleRegion() const { return mVisibleRegion; }
1286
  const ScrollMetadata& GetScrollMetadata(uint32_t aIndex) const;
1287
  const FrameMetrics& GetFrameMetrics(uint32_t aIndex) const;
1288
  uint32_t GetScrollMetadataCount() const { return mScrollMetadata.Length(); }
1289
  const nsTArray<ScrollMetadata>& GetAllScrollMetadata() { return mScrollMetadata; }
1290
  bool HasScrollableFrameMetrics() const;
1291
  bool HasRootScrollableFrameMetrics() const;
1292
  bool IsScrollableWithoutContent() const;
1293
  const EventRegions& GetEventRegions() const { return mEventRegions; }
1294
  ContainerLayer* GetParent() { return mParent; }
1295
  Layer* GetNextSibling() {
1296
    if (mNextSibling) {
1297
      mNextSibling->CheckCanary();
1298
    }
1299
    return mNextSibling;
1300
  }
1301
  const Layer* GetNextSibling() const {
1302
    if (mNextSibling) {
1303
      mNextSibling->CheckCanary();
1304
    }
1305
    return mNextSibling;
1306
  }
1307
  Layer* GetPrevSibling() { return mPrevSibling; }
1308
  const Layer* GetPrevSibling() const { return mPrevSibling; }
1309
0
  virtual Layer* GetFirstChild() const { return nullptr; }
1310
0
  virtual Layer* GetLastChild() const { return nullptr; }
1311
  gfx::Matrix4x4 GetTransform() const;
1312
  // Same as GetTransform(), but returns the transform as a strongly-typed
1313
  // matrix. Eventually this will replace GetTransform().
1314
  const CSSTransformMatrix GetTransformTyped() const;
1315
  const gfx::Matrix4x4& GetBaseTransform() const { return mSimpleAttrs.GetTransform(); }
1316
  // Note: these are virtual because ContainerLayerComposite overrides them.
1317
0
  virtual float GetPostXScale() const { return mSimpleAttrs.GetPostXScale(); }
1318
0
  virtual float GetPostYScale() const { return mSimpleAttrs.GetPostYScale(); }
1319
  bool GetIsFixedPosition() { return mSimpleAttrs.IsFixedPosition(); }
1320
  bool GetTransformIsPerspective() const { return mSimpleAttrs.GetTransformIsPerspective(); }
1321
  bool GetIsStickyPosition() { return mSimpleAttrs.IsStickyPosition(); }
1322
  FrameMetrics::ViewID GetFixedPositionScrollContainerId() { return mSimpleAttrs.GetFixedPositionScrollContainerId(); }
1323
  LayerPoint GetFixedPositionAnchor() { return mSimpleAttrs.GetFixedPositionAnchor(); }
1324
  int32_t GetFixedPositionSides() { return mSimpleAttrs.GetFixedPositionSides(); }
1325
  FrameMetrics::ViewID GetStickyScrollContainerId() { return mSimpleAttrs.GetStickyScrollContainerId(); }
1326
  const LayerRectAbsolute& GetStickyScrollRangeOuter() { return mSimpleAttrs.GetStickyScrollRangeOuter(); }
1327
  const LayerRectAbsolute& GetStickyScrollRangeInner() { return mSimpleAttrs.GetStickyScrollRangeInner(); }
1328
  const ScrollbarData& GetScrollbarData() const { return mSimpleAttrs.GetScrollbarData(); }
1329
  bool IsScrollbarContainer() const;
1330
  Layer* GetMaskLayer() const { return mMaskLayer; }
1331
  bool HasPendingTransform() const { return mPendingTransform; }
1332
1333
  void CheckCanary() const { mCanary.Check(); }
1334
1335
  // Ancestor mask layers are associated with FrameMetrics, but for simplicity
1336
  // in maintaining the layer tree structure we attach them to the layer.
1337
  size_t GetAncestorMaskLayerCount() const {
1338
    return mAncestorMaskLayers.Length();
1339
  }
1340
  Layer* GetAncestorMaskLayerAt(size_t aIndex) const {
1341
    return mAncestorMaskLayers.ElementAt(aIndex);
1342
  }
1343
  const nsTArray<RefPtr<Layer>>& GetAllAncestorMaskLayers() const {
1344
    return mAncestorMaskLayers;
1345
  }
1346
1347
  bool HasMaskLayers() const {
1348
    return GetMaskLayer() || mAncestorMaskLayers.Length() > 0;
1349
  }
1350
1351
  /*
1352
   * Get the combined clip rect of the Layer clip and all clips on FrameMetrics.
1353
   * This is intended for use in Layout. The compositor needs to apply async
1354
   * transforms to find the combined clip.
1355
   */
1356
  Maybe<ParentLayerIntRect> GetCombinedClipRect() const;
1357
1358
  /**
1359
   * Retrieve the root level visible region for |this| taking into account
1360
   * clipping applied to parent layers of |this| as well as subtracting
1361
   * visible regions of higher siblings of this layer and each ancestor.
1362
   *
1363
   * Note translation values for offsets of visible regions and accumulated
1364
   * aLayerOffset are integer rounded using IntPoint::Round.
1365
   *
1366
   * @param aResult - the resulting visible region of this layer.
1367
   * @param aLayerOffset - this layer's total offset from the root layer.
1368
   * @return - false if during layer tree traversal a parent or sibling
1369
   *  transform is found to be non-translational. This method returns early
1370
   *  in this case, results will not be valid. Returns true on successful
1371
   *  traversal.
1372
   */
1373
  bool GetVisibleRegionRelativeToRootLayer(nsIntRegion& aResult,
1374
                                           nsIntPoint* aLayerOffset);
1375
1376
  // Note that all lengths in animation data are either in CSS pixels or app
1377
  // units and must be converted to device pixels by the compositor.
1378
  AnimationArray& GetAnimations() { return mAnimationInfo.GetAnimations(); }
1379
  uint64_t GetCompositorAnimationsId() { return mAnimationInfo.GetCompositorAnimationsId(); }
1380
  InfallibleTArray<AnimData>& GetAnimationData();
1381
1382
  uint64_t GetAnimationGeneration() { return mAnimationInfo.GetAnimationGeneration(); }
1383
1384
  bool HasTransformAnimation() const;
1385
1386
  RawServoAnimationValue* GetBaseAnimationStyle() const
1387
  {
1388
    return mAnimationInfo.GetBaseAnimationStyle();
1389
  }
1390
1391
  /**
1392
   * Returns the local transform for this layer: either mTransform or,
1393
   * for shadow layers, GetShadowBaseTransform(), in either case with the
1394
   * pre- and post-scales applied.
1395
   */
1396
  gfx::Matrix4x4 GetLocalTransform();
1397
1398
  /**
1399
   * Same as GetLocalTransform(), but returns a strongly-typed matrix.
1400
   * Eventually, this will replace GetLocalTransform().
1401
   */
1402
  const LayerToParentLayerMatrix4x4 GetLocalTransformTyped();
1403
1404
  /**
1405
   * Returns the local opacity for this layer: either mOpacity or,
1406
   * for shadow layers, GetShadowOpacity()
1407
   */
1408
  float GetLocalOpacity();
1409
1410
  /**
1411
   * DRAWING PHASE ONLY
1412
   *
1413
   * Apply pending changes to layers before drawing them, if those
1414
   * pending changes haven't been overridden by later changes.
1415
   */
1416
  void ApplyPendingUpdatesToSubtree();
1417
1418
  /**
1419
   * DRAWING PHASE ONLY
1420
   *
1421
   * Write layer-subtype-specific attributes into aAttrs.  Used to
1422
   * synchronize layer attributes to their shadows'.
1423
   */
1424
0
  virtual void FillSpecificAttributes(SpecificLayerAttributes& aAttrs) { }
1425
1426
  // Returns true if it's OK to save the contents of aLayer in an
1427
  // opaque surface (a surface without an alpha channel).
1428
  // If we can use a surface without an alpha channel, we should, because
1429
  // it will often make painting of antialiased text faster and higher
1430
  // quality.
1431
  bool CanUseOpaqueSurface();
1432
1433
  SurfaceMode GetSurfaceMode()
1434
  {
1435
    if (CanUseOpaqueSurface())
1436
      return SurfaceMode::SURFACE_OPAQUE;
1437
    if (GetContentFlags() & CONTENT_COMPONENT_ALPHA)
1438
      return SurfaceMode::SURFACE_COMPONENT_ALPHA;
1439
    return SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
1440
  }
1441
1442
  // Returns true if this layer can be treated as opaque for visibility
1443
  // computation. A layer may be non-opaque for visibility even if it
1444
  // is not transparent, for example, if it has a mix-blend-mode.
1445
  bool IsOpaqueForVisibility();
1446
1447
  /**
1448
   * This setter can be used anytime. The user data for all keys is
1449
   * initially null. Ownership pases to the layer manager.
1450
   */
1451
  void SetUserData(void* aKey, LayerUserData* aData, void (*aDestroy)(void*) = LayerManager::LayerUserDataDestroy)
1452
  {
1453
    mUserData.Add(static_cast<gfx::UserDataKey*>(aKey), aData, aDestroy);
1454
  }
1455
  /**
1456
   * This can be used anytime. Ownership passes to the caller!
1457
   */
1458
  UniquePtr<LayerUserData> RemoveUserData(void* aKey);
1459
  /**
1460
   * This getter can be used anytime.
1461
   */
1462
  bool HasUserData(void* aKey)
1463
  {
1464
    return mUserData.Has(static_cast<gfx::UserDataKey*>(aKey));
1465
  }
1466
  /**
1467
   * This getter can be used anytime. Ownership is retained by the layer
1468
   * manager.
1469
   */
1470
  LayerUserData* GetUserData(void* aKey) const
1471
  {
1472
    return static_cast<LayerUserData*>(mUserData.Get(static_cast<gfx::UserDataKey*>(aKey)));
1473
  }
1474
1475
  /**
1476
   * |Disconnect()| is used by layers hooked up over IPC.  It may be
1477
   * called at any time, and may not be called at all.  Using an
1478
   * IPC-enabled layer after Destroy() (drawing etc.) results in a
1479
   * safe no-op; no crashy or uaf etc.
1480
   *
1481
   * XXX: this interface is essentially LayerManager::Destroy, but at
1482
   * Layer granularity.  It might be beneficial to unify them.
1483
   */
1484
0
  virtual void Disconnect() {}
1485
1486
  /**
1487
   * Dynamic downcast to a PaintedLayer. Returns null if this is not
1488
   * a PaintedLayer.
1489
   */
1490
0
  virtual PaintedLayer* AsPaintedLayer() { return nullptr; }
1491
1492
  /**
1493
   * Dynamic cast to a ContainerLayer. Returns null if this is not
1494
   * a ContainerLayer.
1495
   */
1496
0
  virtual ContainerLayer* AsContainerLayer() { return nullptr; }
1497
0
  virtual const ContainerLayer* AsContainerLayer() const { return nullptr; }
1498
1499
   /**
1500
    * Dynamic cast to a RefLayer. Returns null if this is not a
1501
    * RefLayer.
1502
    */
1503
0
  virtual RefLayer* AsRefLayer() { return nullptr; }
1504
1505
   /**
1506
    * Dynamic cast to a Color. Returns null if this is not a
1507
    * ColorLayer.
1508
    */
1509
0
  virtual ColorLayer* AsColorLayer() { return nullptr; }
1510
1511
  /**
1512
    * Dynamic cast to a Canvas. Returns null if this is not a
1513
    * ColorLayer.
1514
    */
1515
0
  virtual CanvasLayer* AsCanvasLayer() { return nullptr; }
1516
1517
  /**
1518
    * Dynamic cast to an Image. Returns null if this is not a
1519
    * ColorLayer.
1520
    */
1521
  virtual ImageLayer* AsImageLayer() { return nullptr; }
1522
1523
  /**
1524
   * Dynamic cast to a LayerComposite.  Return null if this is not a
1525
   * LayerComposite.  Can be used anytime.
1526
   */
1527
0
  virtual HostLayer* AsHostLayer() { return nullptr; }
1528
1529
  /**
1530
   * Dynamic cast to a ShadowableLayer.  Return null if this is not a
1531
   * ShadowableLayer.  Can be used anytime.
1532
   */
1533
0
  virtual ShadowableLayer* AsShadowableLayer() { return nullptr; }
1534
1535
  // These getters can be used anytime.  They return the effective
1536
  // values that should be used when drawing this layer to screen,
1537
  // accounting for this layer possibly being a shadow.
1538
  const Maybe<ParentLayerIntRect>& GetLocalClipRect();
1539
  const LayerIntRegion& GetLocalVisibleRegion();
1540
1541
  bool Extend3DContext() {
1542
    return GetContentFlags() & CONTENT_EXTEND_3D_CONTEXT;
1543
  }
1544
  bool Combines3DTransformWithAncestors() {
1545
    return GetParent() &&
1546
      reinterpret_cast<Layer*>(GetParent())->Extend3DContext();
1547
  }
1548
  bool Is3DContextLeaf() {
1549
    return !Extend3DContext() && Combines3DTransformWithAncestors();
1550
  }
1551
  /**
1552
   * It is true if the user can see the back of the layer and the
1553
   * backface is hidden.  The compositor should skip the layer if the
1554
   * result is true.
1555
   */
1556
  bool IsBackfaceHidden();
1557
  bool IsVisible() {
1558
    // For containers extending 3D context, visible region
1559
    // is meaningless, since they are just intermediate result of
1560
    // content.
1561
    return !GetLocalVisibleRegion().IsEmpty() || Extend3DContext();
1562
  }
1563
1564
  /**
1565
   * Return true if current layer content is opaque.
1566
   * It does not guarantee that layer content is always opaque.
1567
   */
1568
0
  virtual bool IsOpaque() { return GetContentFlags() & CONTENT_OPAQUE; }
1569
1570
  /**
1571
   * Returns the product of the opacities of this layer and all ancestors up
1572
   * to and excluding the nearest ancestor that has UseIntermediateSurface() set.
1573
   */
1574
  float GetEffectiveOpacity();
1575
1576
  /**
1577
   * Returns the blendmode of this layer.
1578
   */
1579
  gfx::CompositionOp GetEffectiveMixBlendMode();
1580
1581
  /**
1582
   * This returns the effective transform computed by
1583
   * ComputeEffectiveTransforms. Typically this is a transform that transforms
1584
   * this layer all the way to some intermediate surface or destination
1585
   * surface. For non-BasicLayers this will be a transform to the nearest
1586
   * ancestor with UseIntermediateSurface() (or to the root, if there is no
1587
   * such ancestor), but for BasicLayers it's different.
1588
   */
1589
  const gfx::Matrix4x4& GetEffectiveTransform() const { return mEffectiveTransform; }
1590
1591
  /**
1592
   * This returns the effective transform for Layer's buffer computed by
1593
   * ComputeEffectiveTransforms. Typically this is a transform that transforms
1594
   * this layer's buffer all the way to some intermediate surface or destination
1595
   * surface. For non-BasicLayers this will be a transform to the nearest
1596
   * ancestor with UseIntermediateSurface() (or to the root, if there is no
1597
   * such ancestor), but for BasicLayers it's different.
1598
   *
1599
   * By default, its value is same to GetEffectiveTransform().
1600
   * When ImageLayer is rendered with ScaleMode::STRETCH,
1601
   * it becomes different from GetEffectiveTransform().
1602
   */
1603
  virtual const gfx::Matrix4x4& GetEffectiveTransformForBuffer() const
1604
  {
1605
    return mEffectiveTransform;
1606
  }
1607
1608
  /**
1609
   * If the current layers participates in a preserve-3d
1610
   * context (returns true for Combines3DTransformWithAncestors),
1611
   * returns the combined transform up to the preserve-3d (nearest
1612
   * ancestor that doesn't Extend3DContext()). Otherwise returns
1613
   * the local transform.
1614
   */
1615
  gfx::Matrix4x4 ComputeTransformToPreserve3DRoot();
1616
1617
  /**
1618
   * @param aTransformToSurface the composition of the transforms
1619
   * from the parent layer (if any) to the destination pixel grid.
1620
   *
1621
   * Computes mEffectiveTransform for this layer and all its descendants.
1622
   * mEffectiveTransform transforms this layer up to the destination
1623
   * pixel grid (whatever aTransformToSurface is relative to).
1624
   *
1625
   * We promise that when this is called on a layer, all ancestor layers
1626
   * have already had ComputeEffectiveTransforms called.
1627
   */
1628
  virtual void ComputeEffectiveTransforms(const gfx::Matrix4x4& aTransformToSurface) = 0;
1629
1630
  /**
1631
   * Computes the effective transform for mask layers, if this layer has any.
1632
   */
1633
  void ComputeEffectiveTransformForMaskLayers(const gfx::Matrix4x4& aTransformToSurface);
1634
  static void ComputeEffectiveTransformForMaskLayer(Layer* aMaskLayer,
1635
                                                    const gfx::Matrix4x4& aTransformToSurface);
1636
1637
  /**
1638
   * Calculate the scissor rect required when rendering this layer.
1639
   * Returns a rectangle relative to the intermediate surface belonging to the
1640
   * nearest ancestor that has an intermediate surface, or relative to the root
1641
   * viewport if no ancestor has an intermediate surface, corresponding to the
1642
   * clip rect for this layer intersected with aCurrentScissorRect.
1643
   */
1644
  RenderTargetIntRect CalculateScissorRect(const RenderTargetIntRect& aCurrentScissorRect);
1645
1646
  virtual const char* Name() const =0;
1647
  virtual LayerType GetType() const =0;
1648
1649
  /**
1650
   * Only the implementation should call this. This is per-implementation
1651
   * private data. Normally, all layers with a given layer manager
1652
   * use the same type of ImplData.
1653
   */
1654
  void* ImplData() { return mImplData; }
1655
1656
  /**
1657
   * Only the implementation should use these methods.
1658
   */
1659
  void SetParent(ContainerLayer* aParent) { mParent = aParent; }
1660
  void SetNextSibling(Layer* aSibling) { mNextSibling = aSibling; }
1661
  void SetPrevSibling(Layer* aSibling) { mPrevSibling = aSibling; }
1662
1663
  /**
1664
   * Dump information about this layer manager and its managed tree to
1665
   * aStream.
1666
   */
1667
  void Dump(std::stringstream& aStream, const char* aPrefix="",
1668
            bool aDumpHtml=false, bool aSorted=false,
1669
            const Maybe<gfx::Polygon>& aGeometry=Nothing());
1670
  /**
1671
   * Dump information about just this layer manager itself to aStream.
1672
   */
1673
  void DumpSelf(std::stringstream& aStream, const char* aPrefix="",
1674
                const Maybe<gfx::Polygon>& aGeometry=Nothing());
1675
1676
  /**
1677
   * Dump information about this layer and its child & sibling layers to
1678
   * layerscope packet.
1679
   */
1680
  void Dump(layerscope::LayersPacket* aPacket, const void* aParent);
1681
1682
  /**
1683
   * Log information about this layer manager and its managed tree to
1684
   * the NSPR log (if enabled for "Layers").
1685
   */
1686
  void Log(const char* aPrefix="");
1687
  /**
1688
   * Log information about just this layer manager itself to the NSPR
1689
   * log (if enabled for "Layers").
1690
   */
1691
  void LogSelf(const char* aPrefix="");
1692
1693
  // Print interesting information about this into aStream. Internally
1694
  // used to implement Dump*() and Log*(). If subclasses have
1695
  // additional interesting properties, they should override this with
1696
  // an implementation that first calls the base implementation then
1697
  // appends additional info to aTo.
1698
  virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix);
1699
1700
  // Just like PrintInfo, but this function dump information into layerscope packet,
1701
  // instead of a StringStream. It is also internally used to implement Dump();
1702
  virtual void DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent);
1703
1704
  /**
1705
   * Store display list log.
1706
   */
1707
  void SetDisplayListLog(const char *log);
1708
1709
  /**
1710
   * Return display list log.
1711
   */
1712
  void GetDisplayListLog(nsCString& log);
1713
1714
  static bool IsLogEnabled() { return LayerManager::IsLogEnabled(); }
1715
1716
  /**
1717
   * Returns the current area of the layer (in layer-space coordinates)
1718
   * marked as needed to be recomposited.
1719
   */
1720
0
  const virtual gfx::TiledIntRegion& GetInvalidRegion() { return mInvalidRegion; }
1721
  void AddInvalidRegion(const nsIntRegion& aRegion) {
1722
    mInvalidRegion.Add(aRegion);
1723
  }
1724
1725
  /**
1726
   * Mark the entirety of the layer's visible region as being invalid.
1727
   */
1728
  void SetInvalidRectToVisibleRegion()
1729
  {
1730
    mInvalidRegion.SetEmpty();
1731
    mInvalidRegion.Add(GetVisibleRegion().ToUnknownRegion());
1732
  }
1733
1734
  /**
1735
   * Adds to the current invalid rect.
1736
   */
1737
  void AddInvalidRect(const gfx::IntRect& aRect) { mInvalidRegion.Add(aRect); }
1738
1739
  /**
1740
   * Clear the invalid rect, marking the layer as being identical to what is currently
1741
   * composited.
1742
   */
1743
0
  virtual void ClearInvalidRegion() { mInvalidRegion.SetEmpty(); }
1744
1745
  // These functions allow attaching an AsyncPanZoomController to this layer,
1746
  // and can be used anytime.
1747
  // A layer has an APZC at index aIndex only-if GetFrameMetrics(aIndex).IsScrollable();
1748
  // attempting to get an APZC for a non-scrollable metrics will return null.
1749
  // The reverse is also generally true (that if GetFrameMetrics(aIndex).IsScrollable()
1750
  // is true, then the layer will have an APZC). However, it only holds on the
1751
  // the compositor-side layer tree, and only after the APZ code has had a chance
1752
  // to rebuild its internal hit-testing tree using the layer tree. Also, it may
1753
  // not hold in certain "exceptional" scenarios such as if the layer tree
1754
  // doesn't have a GeckoContentController registered for it, or if there is a
1755
  // malicious content process trying to trip up the compositor over IPC.
1756
  // The aIndex for these functions must be less than GetScrollMetadataCount().
1757
  void SetAsyncPanZoomController(uint32_t aIndex, AsyncPanZoomController *controller);
1758
  AsyncPanZoomController* GetAsyncPanZoomController(uint32_t aIndex) const;
1759
  // The ScrollMetadataChanged function is used internally to ensure the APZC array length
1760
  // matches the frame metrics array length.
1761
1762
0
  virtual void ClearCachedResources() {}
1763
1764
0
  virtual bool SupportsAsyncUpdate() { return false; }
1765
private:
1766
  void ScrollMetadataChanged();
1767
public:
1768
1769
  void ApplyPendingUpdatesForThisTransaction();
1770
1771
#ifdef DEBUG
1772
  void SetDebugColorIndex(uint32_t aIndex) { mDebugColorIndex = aIndex; }
1773
  uint32_t GetDebugColorIndex() { return mDebugColorIndex; }
1774
#endif
1775
1776
0
  void Mutated() {
1777
0
    mManager->Mutated(this);
1778
0
  }
1779
  void MutatedSimple() {
1780
    mManager->MutatedSimple(this);
1781
  }
1782
1783
0
  virtual int32_t GetMaxLayerSize() { return Manager()->GetMaxTextureSize(); }
1784
1785
  /**
1786
   * Returns true if this layer's effective transform is not just
1787
   * a translation by integers, or if this layer or some ancestor layer
1788
   * is marked as having a transform that may change without a full layer
1789
   * transaction.
1790
   *
1791
   * Note: This function ignores ancestor layers across layer tree boundaries
1792
   * so that it returns a consistent value when compositing and when painting.
1793
   */
1794
  bool MayResample();
1795
1796
  RenderTargetRect TransformRectToRenderTarget(const LayerIntRect& aRect);
1797
1798
  /**
1799
   * Add debugging information to the layer dump.
1800
   */
1801
  void AddExtraDumpInfo(const nsACString& aStr)
1802
  {
1803
#ifdef MOZ_DUMP_PAINTING
1804
    mExtraDumpInfo.AppendElement(aStr);
1805
#endif
1806
  }
1807
1808
  /**
1809
   * Clear debugging information. Useful for recycling.
1810
   */
1811
  void ClearExtraDumpInfo()
1812
  {
1813
#ifdef MOZ_DUMP_PAINTING
1814
     mExtraDumpInfo.Clear();
1815
#endif
1816
  }
1817
1818
0
  AnimationInfo& GetAnimationInfo() { return mAnimationInfo; }
1819
1820
protected:
1821
  Layer(LayerManager* aManager, void* aImplData);
1822
1823
  // Protected destructor, to discourage deletion outside of Release():
1824
  virtual ~Layer();
1825
1826
  /**
1827
   * We can snap layer transforms for two reasons:
1828
   * 1) To avoid unnecessary resampling when a transform is a translation
1829
   * by a non-integer number of pixels.
1830
   * Snapping the translation to an integer number of pixels avoids
1831
   * blurring the layer and can be faster to composite.
1832
   * 2) When a layer is used to render a rectangular object, we need to
1833
   * emulate the rendering of rectangular inactive content and snap the
1834
   * edges of the rectangle to pixel boundaries. This is both to ensure
1835
   * layer rendering is consistent with inactive content rendering, and to
1836
   * avoid seams.
1837
   * This function implements type 1 snapping. If aTransform is a 2D
1838
   * translation, and this layer's layer manager has enabled snapping
1839
   * (which is the default), return aTransform with the translation snapped
1840
   * to nearest pixels. Otherwise just return aTransform. Call this when the
1841
   * layer does not correspond to a single rectangular content object.
1842
   * This function does not try to snap if aTransform has a scale, because in
1843
   * that case resampling is inevitable and there's no point in trying to
1844
   * avoid it. In fact snapping can cause problems because pixel edges in the
1845
   * layer's content can be rendered unpredictably (jiggling) as the scale
1846
   * interacts with the snapping of the translation, especially with animated
1847
   * transforms.
1848
   * @param aResidualTransform a transform to apply before the result transform
1849
   * in order to get the results to completely match aTransform.
1850
   */
1851
  gfx::Matrix4x4 SnapTransformTranslation(const gfx::Matrix4x4& aTransform,
1852
                                          gfx::Matrix* aResidualTransform);
1853
  gfx::Matrix4x4 SnapTransformTranslation3D(const gfx::Matrix4x4& aTransform,
1854
                                            gfx::Matrix* aResidualTransform);
1855
  /**
1856
   * See comment for SnapTransformTranslation.
1857
   * This function implements type 2 snapping. If aTransform is a translation
1858
   * and/or scale, transform aSnapRect by aTransform, snap to pixel boundaries,
1859
   * and return the transform that maps aSnapRect to that rect. Otherwise
1860
   * just return aTransform.
1861
   * @param aSnapRect a rectangle whose edges should be snapped to pixel
1862
   * boundaries in the destination surface.
1863
   * @param aResidualTransform a transform to apply before the result transform
1864
   * in order to get the results to completely match aTransform.
1865
   */
1866
  gfx::Matrix4x4 SnapTransform(const gfx::Matrix4x4& aTransform,
1867
                               const gfxRect& aSnapRect,
1868
                               gfx::Matrix* aResidualTransform);
1869
1870
  LayerManager* mManager;
1871
  ContainerLayer* mParent;
1872
  Layer* mNextSibling;
1873
  Layer* mPrevSibling;
1874
  void* mImplData;
1875
  RefPtr<Layer> mMaskLayer;
1876
  nsTArray<RefPtr<Layer>> mAncestorMaskLayers;
1877
  // Look for out-of-bound in the middle of the structure
1878
  mozilla::CorruptionCanary mCanary;
1879
  gfx::UserData mUserData;
1880
  SimpleLayerAttributes mSimpleAttrs;
1881
  LayerIntRegion mVisibleRegion;
1882
  nsTArray<ScrollMetadata> mScrollMetadata;
1883
  EventRegions mEventRegions;
1884
  // A mutation of |mTransform| that we've queued to be applied at the
1885
  // end of the next transaction (if nothing else overrides it in the
1886
  // meantime).
1887
  nsAutoPtr<gfx::Matrix4x4> mPendingTransform;
1888
  gfx::Matrix4x4 mEffectiveTransform;
1889
  AnimationInfo mAnimationInfo;
1890
  Maybe<ParentLayerIntRect> mClipRect;
1891
  gfx::IntRect mTileSourceRect;
1892
  gfx::TiledIntRegion mInvalidRegion;
1893
  nsTArray<RefPtr<AsyncPanZoomController> > mApzcs;
1894
  bool mUseTileSourceRect;
1895
#ifdef DEBUG
1896
  uint32_t mDebugColorIndex;
1897
#endif
1898
#ifdef MOZ_DUMP_PAINTING
1899
  nsTArray<nsCString> mExtraDumpInfo;
1900
#endif
1901
  // Store display list log.
1902
  nsCString mDisplayListLog;
1903
};
1904
1905
/**
1906
 * A Layer which we can paint into. It is a conceptually
1907
 * infinite surface, but each PaintedLayer has an associated "valid region"
1908
 * of contents that it is currently storing, which is finite. PaintedLayer
1909
 * implementations can store content between paints.
1910
 *
1911
 * PaintedLayers are rendered into during the drawing phase of a transaction.
1912
 *
1913
 * Currently the contents of a PaintedLayer are in the device output color
1914
 * space.
1915
 */
1916
class PaintedLayer : public Layer {
1917
public:
1918
  /**
1919
   * CONSTRUCTION PHASE ONLY
1920
   * Tell this layer that the content in some region has changed and
1921
   * will need to be repainted. This area is removed from the valid
1922
   * region.
1923
   */
1924
  virtual void InvalidateRegion(const nsIntRegion& aRegion) = 0;
1925
  /**
1926
   * CONSTRUCTION PHASE ONLY
1927
   * Set whether ComputeEffectiveTransforms should compute the
1928
   * "residual translation" --- the translation that should be applied *before*
1929
   * mEffectiveTransform to get the ideal transform for this PaintedLayer.
1930
   * When this is true, ComputeEffectiveTransforms will compute the residual
1931
   * and ensure that the layer is invalidated whenever the residual changes.
1932
   * When it's false, a change in the residual will not trigger invalidation
1933
   * and GetResidualTranslation will return 0,0.
1934
   * So when the residual is to be ignored, set this to false for better
1935
   * performance.
1936
   */
1937
  void SetAllowResidualTranslation(bool aAllow) { mAllowResidualTranslation = aAllow; }
1938
1939
  void SetValidRegion(const nsIntRegion& aRegion)
1940
  {
1941
    MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ValidRegion", this));
1942
    mValidRegion = aRegion;
1943
    mValidRegionIsCurrent = true;
1944
    Mutated();
1945
  }
1946
1947
  /**
1948
   * Can be used anytime
1949
   */
1950
  const nsIntRegion& GetValidRegion() const
1951
  {
1952
    EnsureValidRegionIsCurrent();
1953
    return mValidRegion;
1954
  }
1955
1956
  void InvalidateWholeLayer()
1957
  {
1958
    mInvalidRegion.Add(GetValidRegion().GetBounds());
1959
    ClearValidRegion();
1960
  }
1961
1962
  void ClearValidRegion()
1963
  {
1964
    mValidRegion.SetEmpty();
1965
    mValidRegionIsCurrent = true;
1966
  }
1967
  void AddToValidRegion(const nsIntRegion& aRegion)
1968
  {
1969
    EnsureValidRegionIsCurrent();
1970
    mValidRegion.OrWith(aRegion);
1971
  }
1972
  void SubtractFromValidRegion(const nsIntRegion& aRegion)
1973
  {
1974
    EnsureValidRegionIsCurrent();
1975
    mValidRegion.SubOut(aRegion);
1976
  }
1977
  void UpdateValidRegionAfterInvalidRegionChanged()
1978
  {
1979
    // Changes to mInvalidRegion will be applied to mValidRegion on the next
1980
    // call to EnsureValidRegionIsCurrent().
1981
    mValidRegionIsCurrent = false;
1982
  }
1983
1984
  void ClearInvalidRegion() override
1985
  {
1986
    // mInvalidRegion is about to be reset. This is the last chance to apply
1987
    // any pending changes from it to mValidRegion. Do that by calling
1988
    // EnsureValidRegionIsCurrent().
1989
    EnsureValidRegionIsCurrent();
1990
    mInvalidRegion.SetEmpty();
1991
  }
1992
1993
  virtual PaintedLayer* AsPaintedLayer() override { return this; }
1994
1995
  MOZ_LAYER_DECL_NAME("PaintedLayer", TYPE_PAINTED)
1996
1997
  virtual void ComputeEffectiveTransforms(const gfx::Matrix4x4& aTransformToSurface) override
1998
  {
1999
    gfx::Matrix4x4 idealTransform = GetLocalTransform() * aTransformToSurface;
2000
    gfx::Matrix residual;
2001
    mEffectiveTransform = SnapTransformTranslation(idealTransform,
2002
        mAllowResidualTranslation ? &residual : nullptr);
2003
    // The residual can only be a translation because SnapTransformTranslation
2004
    // only changes the transform if it's a translation
2005
    NS_ASSERTION(residual.IsTranslation(),
2006
                 "Residual transform can only be a translation");
2007
    if (!gfx::ThebesPoint(residual.GetTranslation()).WithinEpsilonOf(mResidualTranslation, 1e-3f)) {
2008
      mResidualTranslation = gfx::ThebesPoint(residual.GetTranslation());
2009
      DebugOnly<mozilla::gfx::Point> transformedOrig =
2010
        idealTransform.TransformPoint(mozilla::gfx::Point());
2011
#ifdef DEBUG
2012
      DebugOnly<mozilla::gfx::Point> transformed = idealTransform.TransformPoint(
2013
        mozilla::gfx::Point(mResidualTranslation.x, mResidualTranslation.y)
2014
      ) - *&transformedOrig;
2015
#endif
2016
      NS_ASSERTION(-0.5 <= (&transformed)->x && (&transformed)->x < 0.5 &&
2017
                   -0.5 <= (&transformed)->y && (&transformed)->y < 0.5,
2018
                   "Residual translation out of range");
2019
      ClearValidRegion();
2020
    }
2021
    ComputeEffectiveTransformForMaskLayers(aTransformToSurface);
2022
  }
2023
2024
  LayerManager::PaintedLayerCreationHint GetCreationHint() const { return mCreationHint; }
2025
2026
  bool UsedForReadback() { return mUsedForReadback; }
2027
  void SetUsedForReadback(bool aUsed) { mUsedForReadback = aUsed; }
2028
2029
  /**
2030
   * Returns true if aLayer is optimized for the given PaintedLayerCreationHint.
2031
   */
2032
  virtual bool IsOptimizedFor(LayerManager::PaintedLayerCreationHint aCreationHint)
2033
  { return true; }
2034
2035
  /**
2036
   * Returns the residual translation. Apply this translation when drawing
2037
   * into the PaintedLayer so that when mEffectiveTransform is applied afterwards
2038
   * by layer compositing, the results exactly match the "ideal transform"
2039
   * (the product of the transform of this layer and its ancestors).
2040
   * Returns 0,0 unless SetAllowResidualTranslation(true) has been called.
2041
   * The residual translation components are always in the range [-0.5, 0.5).
2042
   */
2043
  gfxPoint GetResidualTranslation() const { return mResidualTranslation; }
2044
2045
protected:
2046
  PaintedLayer(LayerManager* aManager, void* aImplData,
2047
              LayerManager::PaintedLayerCreationHint aCreationHint = LayerManager::NONE)
2048
    : Layer(aManager, aImplData)
2049
    , mValidRegion()
2050
    , mValidRegionIsCurrent(true)
2051
    , mCreationHint(aCreationHint)
2052
    , mUsedForReadback(false)
2053
    , mAllowResidualTranslation(false)
2054
0
  {
2055
0
  }
2056
2057
  virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix) override;
2058
2059
  virtual void DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) override;
2060
2061
  /**
2062
   * ComputeEffectiveTransforms snaps the ideal transform to get mEffectiveTransform.
2063
   * mResidualTranslation is the translation that should be applied *before*
2064
   * mEffectiveTransform to get the ideal transform.
2065
   */
2066
  gfxPoint mResidualTranslation;
2067
2068
private:
2069
  /**
2070
   * Needs to be called prior to accessing mValidRegion, unless mValidRegion is
2071
   * being completely overwritten.
2072
   */
2073
  void EnsureValidRegionIsCurrent() const
2074
  {
2075
    if (!mValidRegionIsCurrent) {
2076
      // Apply any pending mInvalidRegion changes to mValidRegion.
2077
      if (!mValidRegion.IsEmpty()) {
2078
        // Calling mInvalidRegion.GetRegion() is expensive.
2079
        // That's why we delay the adjustment of mValidRegion for as long as
2080
        // possible, so that multiple modifications to mInvalidRegion can be
2081
        // applied to mValidRegion in one go.
2082
        mValidRegion.SubOut(mInvalidRegion.GetRegion());
2083
      }
2084
      mValidRegionIsCurrent = true;
2085
    }
2086
  }
2087
2088
  /**
2089
   * The layer's valid region. If mValidRegionIsCurrent is false, then
2090
   * mValidRegion has not yet been updated for recent changes to
2091
   * mInvalidRegion. Those pending changes can be applied by calling
2092
   * EnsureValidRegionIsCurrent().
2093
   */
2094
  mutable nsIntRegion mValidRegion;
2095
2096
  mutable bool mValidRegionIsCurrent;
2097
2098
protected:
2099
  /**
2100
   * The creation hint that was used when constructing this layer.
2101
   */
2102
  const LayerManager::PaintedLayerCreationHint mCreationHint;
2103
  /**
2104
   * Set when this PaintedLayer is participating in readback, i.e. some
2105
   * ReadbackLayer (may) be getting its background from this layer.
2106
   */
2107
  bool mUsedForReadback;
2108
  /**
2109
   * True when
2110
   */
2111
  bool mAllowResidualTranslation;
2112
};
2113
2114
/**
2115
 * A Layer which other layers render into. It holds references to its
2116
 * children.
2117
 */
2118
class ContainerLayer : public Layer {
2119
public:
2120
2121
  ~ContainerLayer();
2122
2123
  /**
2124
   * CONSTRUCTION PHASE ONLY
2125
   * Insert aChild into the child list of this container. aChild must
2126
   * not be currently in any child list or the root for the layer manager.
2127
   * If aAfter is non-null, it must be a child of this container and
2128
   * we insert after that layer. If it's null we insert at the start.
2129
   */
2130
  virtual bool InsertAfter(Layer* aChild, Layer* aAfter);
2131
  /**
2132
   * CONSTRUCTION PHASE ONLY
2133
   * Remove aChild from the child list of this container. aChild must
2134
   * be a child of this container.
2135
   */
2136
  virtual bool RemoveChild(Layer* aChild);
2137
  /**
2138
   * CONSTRUCTION PHASE ONLY
2139
   * Reposition aChild from the child list of this container. aChild must
2140
   * be a child of this container.
2141
   * If aAfter is non-null, it must be a child of this container and we
2142
   * reposition after that layer. If it's null, we reposition at the start.
2143
   */
2144
  virtual bool RepositionChild(Layer* aChild, Layer* aAfter);
2145
2146
  void SetPreScale(float aXScale, float aYScale)
2147
  {
2148
    if (mPreXScale == aXScale && mPreYScale == aYScale) {
2149
      return;
2150
    }
2151
2152
    MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) PreScale", this));
2153
    mPreXScale = aXScale;
2154
    mPreYScale = aYScale;
2155
    Mutated();
2156
  }
2157
2158
  void SetInheritedScale(float aXScale, float aYScale)
2159
  {
2160
    if (mInheritedXScale == aXScale && mInheritedYScale == aYScale) {
2161
      return;
2162
    }
2163
2164
    MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) InheritedScale", this));
2165
    mInheritedXScale = aXScale;
2166
    mInheritedYScale = aYScale;
2167
    Mutated();
2168
  }
2169
2170
  void SetScaleToResolution(bool aScaleToResolution, float aResolution)
2171
  {
2172
    if (mScaleToResolution == aScaleToResolution && mPresShellResolution == aResolution) {
2173
      return;
2174
    }
2175
2176
    MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ScaleToResolution", this));
2177
    mScaleToResolution = aScaleToResolution;
2178
    mPresShellResolution = aResolution;
2179
    Mutated();
2180
  }
2181
2182
  virtual void FillSpecificAttributes(SpecificLayerAttributes& aAttrs) override;
2183
2184
  enum class SortMode {
2185
    WITH_GEOMETRY,
2186
    WITHOUT_GEOMETRY,
2187
  };
2188
2189
  nsTArray<LayerPolygon> SortChildrenBy3DZOrder(SortMode aSortMode);
2190
2191
  virtual ContainerLayer* AsContainerLayer() override { return this; }
2192
  virtual const ContainerLayer* AsContainerLayer() const override { return this; }
2193
2194
  // These getters can be used anytime.
2195
  virtual Layer* GetFirstChild() const override { return mFirstChild; }
2196
  virtual Layer* GetLastChild() const override { return mLastChild; }
2197
  float GetPreXScale() const { return mPreXScale; }
2198
  float GetPreYScale() const { return mPreYScale; }
2199
  float GetInheritedXScale() const { return mInheritedXScale; }
2200
  float GetInheritedYScale() const { return mInheritedYScale; }
2201
  float GetPresShellResolution() const { return mPresShellResolution; }
2202
  bool ScaleToResolution() const { return mScaleToResolution; }
2203
2204
  MOZ_LAYER_DECL_NAME("ContainerLayer", TYPE_CONTAINER)
2205
2206
  /**
2207
   * ContainerLayer backends need to override ComputeEffectiveTransforms
2208
   * since the decision about whether to use a temporary surface for the
2209
   * container is backend-specific. ComputeEffectiveTransforms must also set
2210
   * mUseIntermediateSurface.
2211
   */
2212
  virtual void ComputeEffectiveTransforms(const gfx::Matrix4x4& aTransformToSurface) override = 0;
2213
2214
  /**
2215
   * Call this only after ComputeEffectiveTransforms has been invoked
2216
   * on this layer.
2217
   * Returns true if this will use an intermediate surface. This is largely
2218
   * backend-dependent, but it affects the operation of GetEffectiveOpacity().
2219
   */
2220
  bool UseIntermediateSurface() { return mUseIntermediateSurface; }
2221
2222
  /**
2223
   * Returns the rectangle covered by the intermediate surface,
2224
   * in this layer's coordinate system.
2225
   *
2226
   * NOTE: Since this layer has an intermediate surface it follows
2227
   *       that LayerPixel == RenderTargetPixel
2228
   */
2229
  RenderTargetIntRect GetIntermediateSurfaceRect();
2230
2231
  /**
2232
   * Returns true if this container has more than one non-empty child
2233
   */
2234
  bool HasMultipleChildren();
2235
2236
  /**
2237
   * Returns true if this container supports children with component alpha.
2238
   * Should only be called while painting a child of this layer.
2239
   */
2240
  bool SupportsComponentAlphaChildren() { return mSupportsComponentAlphaChildren; }
2241
2242
  /**
2243
   * Returns true if aLayer or any layer in its parent chain has the opaque
2244
   * content flag set.
2245
   */
2246
  static bool HasOpaqueAncestorLayer(Layer* aLayer);
2247
2248
  void SetChildrenChanged(bool aVal) {
2249
    mChildrenChanged = aVal;
2250
  }
2251
2252
  // If |aRect| is null, the entire layer should be considered invalid for
2253
  // compositing.
2254
  virtual void SetInvalidCompositeRect(const gfx::IntRect* aRect) {}
2255
2256
protected:
2257
  friend class ReadbackProcessor;
2258
2259
  // Note that this is not virtual, and is based on the implementation of
2260
  // ContainerLayer::RemoveChild, so it should only be called where you would
2261
  // want to explicitly call the base class implementation of RemoveChild;
2262
  // e.g., while (mFirstChild) ContainerLayer::RemoveChild(mFirstChild);
2263
  void RemoveAllChildren();
2264
2265
  void DidInsertChild(Layer* aLayer);
2266
  void DidRemoveChild(Layer* aLayer);
2267
2268
  bool AnyAncestorOrThisIs3DContextLeaf();
2269
2270
  void Collect3DContextLeaves(nsTArray<Layer*>& aToSort);
2271
2272
  // Collects child layers that do not extend 3D context. For ContainerLayers
2273
  // that do extend 3D context, the 3D context leaves are collected.
2274
  nsTArray<Layer*> CollectChildren() {
2275
    nsTArray<Layer*> children;
2276
2277
    for (Layer* layer = GetFirstChild(); layer; layer = layer->GetNextSibling()) {
2278
      ContainerLayer* container = layer->AsContainerLayer();
2279
2280
      if (container && container->Extend3DContext() &&
2281
          !container->UseIntermediateSurface()) {
2282
        container->Collect3DContextLeaves(children);
2283
      } else {
2284
        children.AppendElement(layer);
2285
      }
2286
    }
2287
2288
    return children;
2289
  }
2290
2291
  ContainerLayer(LayerManager* aManager, void* aImplData);
2292
2293
  /**
2294
   * A default implementation of ComputeEffectiveTransforms for use by OpenGL
2295
   * and D3D.
2296
   */
2297
  void DefaultComputeEffectiveTransforms(const gfx::Matrix4x4& aTransformToSurface);
2298
2299
  /**
2300
   * A default implementation to compute and set the value for SupportsComponentAlphaChildren().
2301
   *
2302
   * If aNeedsSurfaceCopy is provided, then it is set to true if the caller needs to copy the background
2303
   * up into the intermediate surface created, false otherwise.
2304
   */
2305
  void DefaultComputeSupportsComponentAlphaChildren(bool* aNeedsSurfaceCopy = nullptr);
2306
2307
  /**
2308
   * Loops over the children calling ComputeEffectiveTransforms on them.
2309
   */
2310
  void ComputeEffectiveTransformsForChildren(const gfx::Matrix4x4& aTransformToSurface);
2311
2312
  virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix) override;
2313
2314
  virtual void DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) override;
2315
2316
  /**
2317
   * True for if the container start a new 3D context extended by one
2318
   * or more children.
2319
   */
2320
  bool Creates3DContextWithExtendingChildren();
2321
2322
  Layer* mFirstChild;
2323
  Layer* mLastChild;
2324
  float mPreXScale;
2325
  float mPreYScale;
2326
  // The resolution scale inherited from the parent layer. This will already
2327
  // be part of mTransform.
2328
  float mInheritedXScale;
2329
  float mInheritedYScale;
2330
  // For layers corresponding to an nsDisplayResolution, the resolution of the
2331
  // associated pres shell; for other layers, 1.0.
2332
  float mPresShellResolution;
2333
  // Whether the compositor should scale to mPresShellResolution.
2334
  bool mScaleToResolution;
2335
  bool mUseIntermediateSurface;
2336
  bool mSupportsComponentAlphaChildren;
2337
  bool mMayHaveReadbackChild;
2338
  // This is updated by ComputeDifferences. This will be true if we need to invalidate
2339
  // the intermediate surface.
2340
  bool mChildrenChanged;
2341
};
2342
2343
/**
2344
 * A Layer which just renders a solid color in its visible region. It actually
2345
 * can fill any area that contains the visible region, so if you need to
2346
 * restrict the area filled, set a clip region on this layer.
2347
 */
2348
class ColorLayer : public Layer {
2349
public:
2350
  virtual ColorLayer* AsColorLayer() override { return this; }
2351
2352
  /**
2353
   * CONSTRUCTION PHASE ONLY
2354
   * Set the color of the layer.
2355
   */
2356
  virtual void SetColor(const gfx::Color& aColor)
2357
  {
2358
    if (mColor != aColor) {
2359
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) Color", this));
2360
      mColor = aColor;
2361
      Mutated();
2362
    }
2363
  }
2364
2365
  void SetBounds(const gfx::IntRect& aBounds)
2366
  {
2367
    if (!mBounds.IsEqualEdges(aBounds)) {
2368
      mBounds = aBounds;
2369
      Mutated();
2370
    }
2371
  }
2372
2373
  const gfx::IntRect& GetBounds()
2374
  {
2375
    return mBounds;
2376
  }
2377
2378
  // This getter can be used anytime.
2379
  virtual const gfx::Color& GetColor() { return mColor; }
2380
2381
  MOZ_LAYER_DECL_NAME("ColorLayer", TYPE_COLOR)
2382
2383
  virtual void ComputeEffectiveTransforms(const gfx::Matrix4x4& aTransformToSurface) override
2384
  {
2385
    gfx::Matrix4x4 idealTransform = GetLocalTransform() * aTransformToSurface;
2386
    mEffectiveTransform = SnapTransformTranslation(idealTransform, nullptr);
2387
    ComputeEffectiveTransformForMaskLayers(aTransformToSurface);
2388
  }
2389
2390
protected:
2391
  ColorLayer(LayerManager* aManager, void* aImplData)
2392
    : Layer(aManager, aImplData)
2393
    , mColor()
2394
  {}
2395
2396
  virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix) override;
2397
2398
  virtual void DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) override;
2399
2400
  gfx::IntRect mBounds;
2401
  gfx::Color mColor;
2402
};
2403
2404
/**
2405
 * A Layer for HTML Canvas elements.  It's backed by either a
2406
 * gfxASurface or a GLContext (for WebGL layers), and has some control
2407
 * for intelligent updating from the source if necessary (for example,
2408
 * if hardware compositing is not available, for reading from the GL
2409
 * buffer into an image surface that we can layer composite.)
2410
 *
2411
 * After Initialize is called, the underlying canvas Surface/GLContext
2412
 * must not be modified during a layer transaction.
2413
 */
2414
class CanvasLayer : public Layer {
2415
public:
2416
  void SetBounds(gfx::IntRect aBounds) { mBounds = aBounds; }
2417
2418
  virtual CanvasLayer* AsCanvasLayer() override { return this; }
2419
2420
  /**
2421
   * Notify this CanvasLayer that the canvas surface contents have
2422
   * changed (or will change) before the next transaction.
2423
   */
2424
  void Updated() { mCanvasRenderer->SetDirty(); SetInvalidRectToVisibleRegion(); }
2425
2426
  /**
2427
   * Notify this CanvasLayer that the canvas surface contents have
2428
   * been painted since the last change.
2429
   */
2430
  void Painted() { mCanvasRenderer->ResetDirty(); }
2431
2432
  /**
2433
   * Returns true if the canvas surface contents have changed since the
2434
   * last paint.
2435
   */
2436
  bool IsDirty()
2437
  {
2438
    // We can only tell if we are dirty if we're part of the
2439
    // widget's retained layer tree.
2440
    if (!mManager || !mManager->IsWidgetLayerManager()) {
2441
      return true;
2442
    }
2443
    return mCanvasRenderer->IsDirty();
2444
  }
2445
2446
  const nsIntRect& GetBounds() const { return mBounds; }
2447
2448
  CanvasRenderer* CreateOrGetCanvasRenderer();
2449
2450
public:
2451
2452
  /**
2453
   * CONSTRUCTION PHASE ONLY
2454
   * Set the filter used to resample this image (if necessary).
2455
   */
2456
  void SetSamplingFilter(gfx::SamplingFilter aSamplingFilter)
2457
  {
2458
    if (mSamplingFilter != aSamplingFilter) {
2459
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) Filter", this));
2460
      mSamplingFilter = aSamplingFilter;
2461
      Mutated();
2462
    }
2463
  }
2464
  gfx::SamplingFilter GetSamplingFilter() const { return mSamplingFilter; }
2465
2466
  MOZ_LAYER_DECL_NAME("CanvasLayer", TYPE_CANVAS)
2467
2468
  virtual void ComputeEffectiveTransforms(const gfx::Matrix4x4& aTransformToSurface) override
2469
  {
2470
    // Snap our local transform first, and snap the inherited transform as well.
2471
    // This makes our snapping equivalent to what would happen if our content
2472
    // was drawn into a PaintedLayer (gfxContext would snap using the local
2473
    // transform, then we'd snap again when compositing the PaintedLayer).
2474
    mEffectiveTransform =
2475
      SnapTransform(GetLocalTransform(), gfxRect(0, 0, mBounds.Width(), mBounds.Height()),
2476
                      nullptr)*
2477
        SnapTransformTranslation(aTransformToSurface, nullptr);
2478
    ComputeEffectiveTransformForMaskLayers(aTransformToSurface);
2479
  }
2480
2481
protected:
2482
  CanvasLayer(LayerManager* aManager, void* aImplData);
2483
  virtual ~CanvasLayer();
2484
2485
  virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix) override;
2486
2487
  virtual void DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) override;
2488
2489
  virtual CanvasRenderer* CreateCanvasRendererInternal() = 0;
2490
2491
  UniquePtr<CanvasRenderer> mCanvasRenderer;
2492
  gfx::SamplingFilter mSamplingFilter;
2493
2494
  /**
2495
   * 0, 0, canvaswidth, canvasheight
2496
   */
2497
  gfx::IntRect mBounds;
2498
};
2499
2500
/**
2501
 * ContainerLayer that refers to a "foreign" layer tree, through an
2502
 * ID.  Usage of RefLayer looks like
2503
 *
2504
 * Construction phase:
2505
 *   allocate ID for layer subtree
2506
 *   create RefLayer, SetReferentId(ID)
2507
 *
2508
 * Composition:
2509
 *   look up subtree for GetReferentId()
2510
 *   ConnectReferentLayer(subtree)
2511
 *   compose
2512
 *   ClearReferentLayer()
2513
 *
2514
 * Clients will usually want to Connect/Clear() on each transaction to
2515
 * avoid difficulties managing memory across multiple layer subtrees.
2516
 */
2517
class RefLayer : public ContainerLayer {
2518
  friend class LayerManager;
2519
2520
private:
2521
  virtual bool InsertAfter(Layer* aChild, Layer* aAfter) override
2522
  { MOZ_CRASH("GFX: RefLayer"); return false; }
2523
2524
  virtual bool RemoveChild(Layer* aChild) override
2525
  { MOZ_CRASH("GFX: RefLayer"); return false; }
2526
2527
  virtual bool RepositionChild(Layer* aChild, Layer* aAfter) override
2528
  { MOZ_CRASH("GFX: RefLayer"); return false; }
2529
2530
public:
2531
  /**
2532
   * CONSTRUCTION PHASE ONLY
2533
   * Set the ID of the layer's referent.
2534
   */
2535
  void SetReferentId(LayersId aId)
2536
  {
2537
    MOZ_ASSERT(aId.IsValid());
2538
    if (mId != aId) {
2539
      MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ReferentId", this));
2540
      mId = aId;
2541
      Mutated();
2542
    }
2543
  }
2544
  /**
2545
   * CONSTRUCTION PHASE ONLY
2546
   * Connect this ref layer to its referent, temporarily.
2547
   * ClearReferentLayer() must be called after composition.
2548
   */
2549
  void ConnectReferentLayer(Layer* aLayer)
2550
  {
2551
    MOZ_ASSERT(!mFirstChild && !mLastChild);
2552
    MOZ_ASSERT(!aLayer->GetParent());
2553
    if (aLayer->Manager() != Manager()) {
2554
      // This can happen when e.g. rendering while dragging tabs
2555
      // between windows - aLayer's manager may be the manager for the
2556
      // old window's tab.  In that case, it will be changed before the
2557
      // next render (see SetLayerManager).  It is simply easier to
2558
      // ignore the rendering here than it is to pause it.
2559
      NS_WARNING("ConnectReferentLayer failed - Incorrect LayerManager");
2560
      return;
2561
    }
2562
2563
    mFirstChild = mLastChild = aLayer;
2564
    aLayer->SetParent(this);
2565
  }
2566
2567
  /**
2568
   * CONSTRUCTION PHASE ONLY
2569
   * Set flags that indicate how event regions in the child layer tree need
2570
   * to be overridden because of properties of the parent layer tree.
2571
   */
2572
  void SetEventRegionsOverride(EventRegionsOverride aVal) {
2573
    if (mEventRegionsOverride == aVal) {
2574
      return;
2575
    }
2576
2577
    MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) EventRegionsOverride", this));
2578
    mEventRegionsOverride = aVal;
2579
    Mutated();
2580
  }
2581
2582
  EventRegionsOverride GetEventRegionsOverride() const {
2583
    return mEventRegionsOverride;
2584
  }
2585
2586
  /**
2587
   * DRAWING PHASE ONLY
2588
   * |aLayer| is the same as the argument to ConnectReferentLayer().
2589
   */
2590
  void DetachReferentLayer(Layer* aLayer)
2591
  {
2592
    mFirstChild = mLastChild = nullptr;
2593
    aLayer->SetParent(nullptr);
2594
  }
2595
2596
  // These getters can be used anytime.
2597
  virtual RefLayer* AsRefLayer() override { return this; }
2598
2599
  virtual LayersId GetReferentId() { return mId; }
2600
2601
  /**
2602
   * DRAWING PHASE ONLY
2603
   */
2604
  virtual void FillSpecificAttributes(SpecificLayerAttributes& aAttrs) override;
2605
2606
  MOZ_LAYER_DECL_NAME("RefLayer", TYPE_REF)
2607
2608
protected:
2609
  RefLayer(LayerManager* aManager, void* aImplData)
2610
    : ContainerLayer(aManager, aImplData)
2611
    , mId{0}
2612
    , mEventRegionsOverride(EventRegionsOverride::NoOverride)
2613
  {}
2614
2615
  virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix) override;
2616
2617
  virtual void DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) override;
2618
2619
  // 0 is a special value that means "no ID".
2620
  LayersId mId;
2621
  EventRegionsOverride mEventRegionsOverride;
2622
};
2623
2624
void SetAntialiasingFlags(Layer* aLayer, gfx::DrawTarget* aTarget);
2625
2626
#ifdef MOZ_DUMP_PAINTING
2627
void WriteSnapshotToDumpFile(Layer* aLayer, gfx::DataSourceSurface* aSurf);
2628
void WriteSnapshotToDumpFile(LayerManager* aManager, gfx::DataSourceSurface* aSurf);
2629
void WriteSnapshotToDumpFile(Compositor* aCompositor, gfx::DrawTarget* aTarget);
2630
#endif
2631
2632
// A utility function used by different LayerManager implementations.
2633
gfx::IntRect ToOutsideIntRect(const gfxRect &aRect);
2634
2635
} // namespace layers
2636
} // namespace mozilla
2637
2638
#endif /* GFX_LAYERS_H */