summaryrefslogtreecommitdiffstats
path: root/gfx/layers/client/ContentClient.cpp
blob: 4e465f0a02ded0d06a6e5c01a23c1867def1cfa4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/layers/ContentClient.h"
#include "BasicLayers.h"  // for BasicLayerManager
#include "gfxContext.h"   // for gfxContext, etc
#include "gfxPlatform.h"  // for gfxPlatform
#include "gfxEnv.h"       // for gfxEnv

#include "gfxPoint.h"               // for IntSize, gfxPoint
#include "gfxUtils.h"               // for gfxUtils
#include "ipc/ShadowLayers.h"       // for ShadowLayerForwarder
#include "mozilla/ArrayUtils.h"     // for ArrayLength
#include "mozilla/gfx/2D.h"         // for DrawTarget, Factory
#include "mozilla/gfx/BasePoint.h"  // for BasePoint
#include "mozilla/gfx/BaseSize.h"   // for BaseSize
#include "mozilla/gfx/Rect.h"       // for Rect
#include "mozilla/gfx/Types.h"
#include "mozilla/layers/CompositorBridgeChild.h"  // for CompositorBridgeChild
#include "mozilla/layers/LayerManagerComposite.h"
#include "mozilla/layers/LayersMessages.h"  // for ThebesBufferData
#include "mozilla/layers/LayersTypes.h"
#include "mozilla/layers/PaintThread.h"
#include "nsDebug.h"          // for NS_ASSERTION, NS_WARNING, etc
#include "nsISupportsImpl.h"  // for gfxContext::Release, etc
#include "nsIWidget.h"        // for nsIWidget
#include "nsLayoutUtils.h"
#ifdef XP_WIN
#  include "gfxWindowsPlatform.h"
#endif
#ifdef MOZ_WIDGET_GTK
#  include "gfxPlatformGtk.h"
#endif
#ifdef MOZ_WAYLAND
#  include "mozilla/widget/nsWaylandDisplay.h"
#endif
#include "ReadbackLayer.h"

#include <utility>
#include <vector>

namespace mozilla {

using namespace gfx;

namespace layers {

static TextureFlags TextureFlagsForContentClientFlags(uint32_t aBufferFlags) {
  TextureFlags result = TextureFlags::NO_FLAGS;

  if (aBufferFlags & ContentClient::BUFFER_COMPONENT_ALPHA) {
    result |= TextureFlags::COMPONENT_ALPHA;
  }

  return result;
}

static IntRect ComputeBufferRect(const IntRect& aRequestedRect) {
  IntRect rect(aRequestedRect);
  // Set a minimum width to guarantee a minimum size of buffers we
  // allocate (and work around problems on some platforms with smaller
  // dimensions). 64 used to be the magic number needed to work around
  // a rendering glitch on b2g (see bug 788411). Now that we don't support
  // this device anymore we should be fine with 8 pixels as the minimum.
  rect.SetWidth(std::max(aRequestedRect.Width(), 8));
  return rect;
}

/* static */
already_AddRefed<ContentClient> ContentClient::CreateContentClient(
    CompositableForwarder* aForwarder) {
  LayersBackend backend = aForwarder->GetCompositorBackendType();
  if (backend != LayersBackend::LAYERS_OPENGL &&
      backend != LayersBackend::LAYERS_D3D11 &&
      backend != LayersBackend::LAYERS_WR &&
      backend != LayersBackend::LAYERS_BASIC) {
    return nullptr;
  }

  bool useDoubleBuffering = false;

#ifdef XP_WIN
  if (backend == LayersBackend::LAYERS_D3D11) {
    useDoubleBuffering = gfxWindowsPlatform::GetPlatform()->IsDirect2DBackend();
  } else
#endif
  {
#ifdef MOZ_WIDGET_GTK
#  ifdef MOZ_WAYLAND
    if (widget::GetDMABufDevice()->IsDMABufTexturesEnabled()) {
      useDoubleBuffering = true;
    } else
#  endif
        // We can't use double buffering when using image content with
        // Xrender support on Linux, as ContentHostDoubleBuffered is not
        // suited for direct uploads to the server.
        if (!gfxPlatformGtk::GetPlatform()->UseImageOffscreenSurfaces() ||
            !gfxVars::UseXRender())
#endif
    {
      useDoubleBuffering = backend == LayersBackend::LAYERS_BASIC;
    }
  }

  if (useDoubleBuffering || gfxEnv::ForceDoubleBuffering()) {
    return MakeAndAddRef<ContentClientDoubleBuffered>(aForwarder);
  }
  return MakeAndAddRef<ContentClientSingleBuffered>(aForwarder);
}

void ContentClient::Clear() { mBuffer = nullptr; }

ContentClient::PaintState ContentClient::BeginPaint(PaintedLayer* aLayer,
                                                    uint32_t aFlags) {
  BufferDecision dest = CalculateBufferForPaint(aLayer, aFlags);

  PaintState result;
  result.mAsyncPaint = (aFlags & PAINT_ASYNC);
  result.mContentType = dest.mBufferContentType;

  if (!dest.mCanKeepBufferContents) {
    // We're effectively clearing the valid region, so we need to draw
    // the entire needed region now.
    MOZ_ASSERT(!dest.mCanReuseBuffer);
    MOZ_ASSERT(dest.mValidRegion.IsEmpty());

    result.mRegionToInvalidate = aLayer->GetValidRegion();

#if defined(MOZ_DUMP_PAINTING)
    if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
      if (result.mContentType != mBuffer->GetContentType()) {
        printf_stderr(
            "Invalidating entire rotated buffer (layer %p): content type "
            "changed\n",
            aLayer);
      } else if ((dest.mBufferMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) !=
                 mBuffer->HaveBufferOnWhite()) {
        printf_stderr(
            "Invalidating entire rotated buffer (layer %p): component alpha "
            "changed\n",
            aLayer);
      }
    }
#endif
    Clear();
  }

  result.mRegionToDraw.Sub(dest.mNeededRegion, dest.mValidRegion);

  if (result.mRegionToDraw.IsEmpty()) return result;

  // We need to disable rotation if we're going to be resampled when
  // drawing, because we might sample across the rotation boundary.
  // Also disable buffer rotation when using webrender.
  bool canHaveRotation =
      gfxPlatform::BufferRotationEnabled() &&
      !(aFlags & (PAINT_WILL_RESAMPLE | PAINT_NO_ROTATION)) &&
      !(aLayer->Manager()->AsWebRenderLayerManager());
  bool canDrawRotated = aFlags & PAINT_CAN_DRAW_ROTATED;
  OpenMode readMode =
      result.mAsyncPaint ? OpenMode::OPEN_READ_ASYNC : OpenMode::OPEN_READ;
  OpenMode writeMode = result.mAsyncPaint ? OpenMode::OPEN_READ_WRITE_ASYNC
                                          : OpenMode::OPEN_READ_WRITE;

  IntRect drawBounds = result.mRegionToDraw.GetBounds();

  if (result.mAsyncPaint) {
    result.mAsyncTask.reset(new PaintTask());
  }

  // Try to acquire the back buffer, copy over contents if we are using a new
  // buffer, and rotate or unrotate the buffer as necessary
  if (mBuffer && dest.mCanReuseBuffer) {
    if (mBuffer->Lock(writeMode)) {
      auto newParameters = mBuffer->AdjustedParameters(dest.mBufferRect);

      bool needsUnrotate =
          (!canHaveRotation && newParameters.IsRotated()) ||
          (!canDrawRotated && newParameters.RectWrapsBuffer(drawBounds));
      bool canUnrotate =
          !result.mAsyncPaint || mBuffer->BufferRotation() == IntPoint(0, 0);

      // Only begin a frame and copy over the previous frame if we don't need
      // to unrotate, or we can try to unrotate it. This is to ensure that we
      // don't have a paint task that depends on another paint task.
      if (!needsUnrotate || canUnrotate) {
        // If we're async painting then begin to capture draw commands
        if (result.mAsyncPaint) {
          mBuffer->BeginCapture();
        }

        // Do not modify result.mRegionToDraw or result.mContentType after this
        // call.
        FinalizeFrame(result);
      }

      // Try to rotate the buffer or unrotate it if we cannot be rotated
      if (needsUnrotate) {
        if (canUnrotate && mBuffer->UnrotateBufferTo(newParameters)) {
          newParameters.SetUnrotated();
          mBuffer->SetParameters(newParameters);
        } else {
          MOZ_ASSERT(GetFrontBuffer());
          mBuffer->Unlock();
          dest.mBufferRect = ComputeBufferRect(dest.mNeededRegion.GetBounds());
          dest.mCanReuseBuffer = false;
        }
      } else {
        mBuffer->SetParameters(newParameters);
      }
    } else {
      result.mRegionToDraw = dest.mNeededRegion;
      dest.mCanReuseBuffer = false;
      Clear();
    }
  }

  MOZ_ASSERT(dest.mBufferRect.Contains(result.mRegionToDraw.GetBounds()));

  NS_ASSERTION(!(aFlags & PAINT_WILL_RESAMPLE) ||
                   dest.mBufferRect == dest.mNeededRegion.GetBounds(),
               "If we're resampling, we need to validate the entire buffer");

  // We never had a buffer, the buffer wasn't big enough, the content changed
  // types, or we failed to unrotate the buffer when requested. In any case,
  // we need to allocate a new one and prepare it for drawing.
  if (!dest.mCanReuseBuffer) {
    uint32_t bufferFlags = 0;
    if (dest.mBufferMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
      bufferFlags |= BUFFER_COMPONENT_ALPHA;
    }

    RefPtr<RotatedBuffer> newBuffer =
        CreateBuffer(result.mContentType, dest.mBufferRect, bufferFlags);

    if (!newBuffer) {
      if (Factory::ReasonableSurfaceSize(
              IntSize(dest.mBufferRect.Width(), dest.mBufferRect.Height()))) {
        gfxCriticalNote << "Failed buffer for " << dest.mBufferRect.X() << ", "
                        << dest.mBufferRect.Y() << ", "
                        << dest.mBufferRect.Width() << ", "
                        << dest.mBufferRect.Height();
      }
      result.mAsyncTask = nullptr;
      Clear();
      return result;
    }

    if (!newBuffer->Lock(writeMode)) {
      gfxCriticalNote << "Failed to lock new back buffer.";
      result.mAsyncTask = nullptr;
      Clear();
      return result;
    }

    if (result.mAsyncPaint) {
      newBuffer->BeginCapture();
    }

    // If we have an existing front buffer, copy it into the new back buffer
    RefPtr<RotatedBuffer> frontBuffer = GetFrontBuffer();

    if (frontBuffer && frontBuffer->Lock(readMode)) {
      nsIntRegion updateRegion = newBuffer->BufferRect();
      updateRegion.Sub(updateRegion, result.mRegionToDraw);

      if (!updateRegion.IsEmpty()) {
        newBuffer->UpdateDestinationFrom(*frontBuffer,
                                         updateRegion.GetBounds());
      }

      frontBuffer->Unlock();
    } else {
      result.mRegionToDraw = dest.mNeededRegion;
    }

    Clear();
    mBuffer = newBuffer;
  }

  NS_ASSERTION(canHaveRotation || mBuffer->BufferRotation() == IntPoint(0, 0),
               "Rotation disabled, but we have nonzero rotation?");

  if (result.mAsyncPaint) {
    result.mAsyncTask->mTarget = mBuffer->GetBufferTarget();
    result.mAsyncTask->mClients.AppendElement(mBuffer->GetClient());
    if (mBuffer->GetClientOnWhite()) {
      result.mAsyncTask->mClients.AppendElement(mBuffer->GetClientOnWhite());
    }
  }

  nsIntRegion invalidate;
  invalidate.Sub(aLayer->GetValidRegion(), dest.mBufferRect);
  result.mRegionToInvalidate.Or(result.mRegionToInvalidate, invalidate);

  result.mClip = DrawRegionClip::DRAW;
  result.mMode = dest.mBufferMode;

  return result;
}

void ContentClient::EndPaint(
    PaintState& aPaintState,
    nsTArray<ReadbackProcessor::Update>* aReadbackUpdates) {
  if (aPaintState.mAsyncTask) {
    aPaintState.mAsyncTask->mCapture = mBuffer->EndCapture();
  }
}

static nsIntRegion ExpandDrawRegion(ContentClient::PaintState& aPaintState,
                                    RotatedBuffer::DrawIterator* aIter,
                                    BackendType aBackendType) {
  nsIntRegion* drawPtr = &aPaintState.mRegionToDraw;
  if (aIter) {
    // The iterators draw region currently only contains the bounds of the
    // region, this makes it the precise region.
    aIter->mDrawRegion.And(aIter->mDrawRegion, aPaintState.mRegionToDraw);
    drawPtr = &aIter->mDrawRegion;
  }
  if (aBackendType == BackendType::DIRECT2D ||
      aBackendType == BackendType::DIRECT2D1_1) {
    // Simplify the draw region to avoid hitting expensive drawing paths
    // for complex regions.
    drawPtr->SimplifyOutwardByArea(100 * 100);
  }
  return *drawPtr;
}

DrawTarget* ContentClient::BorrowDrawTargetForPainting(
    ContentClient::PaintState& aPaintState,
    RotatedBuffer::DrawIterator* aIter /* = nullptr */) {
  if (aPaintState.mMode == SurfaceMode::SURFACE_NONE || !mBuffer) {
    return nullptr;
  }

  DrawTarget* result = mBuffer->BorrowDrawTargetForQuadrantUpdate(
      aPaintState.mRegionToDraw.GetBounds(), aIter);
  if (!result || !result->IsValid()) {
    if (result) {
      mBuffer->ReturnDrawTarget(result);
    }
    return nullptr;
  }

  nsIntRegion regionToDraw =
      ExpandDrawRegion(aPaintState, aIter, result->GetBackendType());

  if (aPaintState.mMode == SurfaceMode::SURFACE_COMPONENT_ALPHA ||
      aPaintState.mContentType == gfxContentType::COLOR_ALPHA) {
    // HaveBuffer() => we have an existing buffer that we must clear
    for (auto iter = regionToDraw.RectIter(); !iter.Done(); iter.Next()) {
      const IntRect& rect = iter.Get();
      result->ClearRect(Rect(rect.X(), rect.Y(), rect.Width(), rect.Height()));
    }
  }

  return result;
}

void ContentClient::ReturnDrawTarget(gfx::DrawTarget*& aReturned) {
  mBuffer->ReturnDrawTarget(aReturned);
}

ContentClient::BufferDecision ContentClient::CalculateBufferForPaint(
    PaintedLayer* aLayer, uint32_t aFlags) {
  gfxContentType layerContentType = aLayer->CanUseOpaqueSurface()
                                        ? gfxContentType::COLOR
                                        : gfxContentType::COLOR_ALPHA;

  SurfaceMode mode;
  gfxContentType contentType;
  IntRect destBufferRect;
  nsIntRegion neededRegion;
  nsIntRegion validRegion = aLayer->GetValidRegion();

  bool canReuseBuffer = !!mBuffer;
  bool canKeepBufferContents = true;

  while (true) {
    mode = aLayer->GetSurfaceMode();
    neededRegion = aLayer->GetVisibleRegion().ToUnknownRegion();
    canReuseBuffer =
        canReuseBuffer &&
        ValidBufferSize(mBufferSizePolicy, mBuffer->BufferRect().Size(),
                        neededRegion.GetBounds().Size());
    contentType = layerContentType;

    if (canReuseBuffer) {
      if (mBuffer->BufferRect().Contains(neededRegion.GetBounds())) {
        // We don't need to adjust mBufferRect.
        destBufferRect = mBuffer->BufferRect();
      } else if (neededRegion.GetBounds().Size() <=
                 mBuffer->BufferRect().Size()) {
        // The buffer's big enough but doesn't contain everything that's
        // going to be visible. We'll move it.
        destBufferRect = IntRect(neededRegion.GetBounds().TopLeft(),
                                 mBuffer->BufferRect().Size());
      } else {
        destBufferRect = neededRegion.GetBounds();
      }
    } else {
      destBufferRect = ComputeBufferRect(neededRegion.GetBounds());
    }

    if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
#if defined(MOZ_GFX_OPTIMIZE_MOBILE)
      mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
#else
      if (!aLayer->GetParent() ||
          !aLayer->GetParent()->SupportsComponentAlphaChildren() ||
          !aLayer->AsShadowableLayer() ||
          !aLayer->AsShadowableLayer()->HasShadow()) {
        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
      } else {
        contentType = gfxContentType::COLOR;
      }
#endif
    }

    if ((aFlags & PAINT_WILL_RESAMPLE) &&
        (!neededRegion.GetBounds().IsEqualInterior(destBufferRect) ||
         neededRegion.GetNumRects() > 1)) {
      // The area we add to neededRegion might not be painted opaquely.
      if (mode == SurfaceMode::SURFACE_OPAQUE) {
        contentType = gfxContentType::COLOR_ALPHA;
        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
      }

      // We need to validate the entire buffer, to make sure that only valid
      // pixels are sampled.
      neededRegion = destBufferRect;
    }

    // If we have an existing buffer, but the content type has changed or we
    // have transitioned into/out of component alpha, then we need to recreate
    // it.
    bool needsComponentAlpha = (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA);
    bool backBufferChangedSurface =
        mBuffer && (contentType != mBuffer->GetContentType() ||
                    needsComponentAlpha != mBuffer->HaveBufferOnWhite());
    if (canKeepBufferContents && backBufferChangedSurface) {
      // Restart the decision process; we won't re-enter since we guard on
      // being able to keep the buffer contents.
      canReuseBuffer = false;
      canKeepBufferContents = false;
      validRegion.SetEmpty();
      continue;
    }
    break;
  }

  NS_ASSERTION(destBufferRect.Contains(neededRegion.GetBounds()),
               "Destination rect doesn't contain what we need to paint");

  BufferDecision dest;
  dest.mNeededRegion = std::move(neededRegion);
  dest.mValidRegion = std::move(validRegion);
  dest.mBufferRect = destBufferRect;
  dest.mBufferMode = mode;
  dest.mBufferContentType = contentType;
  dest.mCanReuseBuffer = canReuseBuffer;
  dest.mCanKeepBufferContents = canKeepBufferContents;
  return dest;
}

bool ContentClient::ValidBufferSize(BufferSizePolicy aPolicy,
                                    const gfx::IntSize& aBufferSize,
                                    const gfx::IntSize& aVisibleBoundsSize) {
  return (
      aVisibleBoundsSize == aBufferSize ||
      (SizedToVisibleBounds != aPolicy && aVisibleBoundsSize < aBufferSize));
}

void ContentClient::PrintInfo(std::stringstream& aStream, const char* aPrefix) {
  aStream << aPrefix;
  aStream << nsPrintfCString("ContentClient (0x%p)", this).get();
}

// We pass a null pointer for the ContentClient Forwarder argument, which means
// this client will not have a ContentHost on the other side.
ContentClientBasic::ContentClientBasic(gfx::BackendType aBackend)
    : ContentClient(nullptr, ContainsVisibleBounds), mBackend(aBackend) {}

void ContentClientBasic::DrawTo(PaintedLayer* aLayer, gfx::DrawTarget* aTarget,
                                float aOpacity, gfx::CompositionOp aOp,
                                gfx::SourceSurface* aMask,
                                const gfx::Matrix* aMaskTransform) {
  if (!mBuffer) {
    return;
  }

  mBuffer->DrawTo(aLayer, aTarget, aOpacity, aOp, aMask, aMaskTransform);
}

RefPtr<RotatedBuffer> ContentClientBasic::CreateBuffer(gfxContentType aType,
                                                       const IntRect& aRect,
                                                       uint32_t aFlags) {
  MOZ_ASSERT(!(aFlags & BUFFER_COMPONENT_ALPHA));
  if (aFlags & BUFFER_COMPONENT_ALPHA) {
    gfxDevCrash(LogReason::AlphaWithBasicClient)
        << "Asking basic content client for component alpha";
  }

  IntSize size(aRect.Width(), aRect.Height());
  RefPtr<gfx::DrawTarget> drawTarget;

#ifdef XP_WIN
  if (mBackend == BackendType::CAIRO &&
      (aType == gfxContentType::COLOR ||
       aType == gfxContentType::COLOR_ALPHA)) {
    RefPtr<gfxASurface> surf = new gfxWindowsSurface(
        size, aType == gfxContentType::COLOR ? gfxImageFormat::X8R8G8B8_UINT32
                                             : gfxImageFormat::A8R8G8B8_UINT32);
    drawTarget = gfxPlatform::CreateDrawTargetForSurface(surf, size);
  }
#endif

  if (!drawTarget) {
    drawTarget = gfxPlatform::GetPlatform()->CreateDrawTargetForBackend(
        mBackend, size,
        gfxPlatform::GetPlatform()->Optimal2DFormatForContent(aType));
  }

  if (!drawTarget) {
    return nullptr;
  }

  return new DrawTargetRotatedBuffer(drawTarget, nullptr, aRect,
                                     IntPoint(0, 0));
}

class RemoteBufferReadbackProcessor : public TextureReadbackSink {
 public:
  RemoteBufferReadbackProcessor(
      nsTArray<ReadbackProcessor::Update>* aReadbackUpdates,
      const IntRect& aBufferRect, const nsIntPoint& aBufferRotation)
      : mReadbackUpdates(aReadbackUpdates->Clone()),
        mBufferRect(aBufferRect),
        mBufferRotation(aBufferRotation) {
    for (uint32_t i = 0; i < mReadbackUpdates.Length(); ++i) {
      mLayerRefs.push_back(mReadbackUpdates[i].mLayer);
    }
  }

  virtual void ProcessReadback(
      gfx::DataSourceSurface* aSourceSurface) override {
    SourceRotatedBuffer rotBuffer(aSourceSurface, nullptr, mBufferRect,
                                  mBufferRotation);

    for (uint32_t i = 0; i < mReadbackUpdates.Length(); ++i) {
      ReadbackProcessor::Update& update = mReadbackUpdates[i];
      nsIntPoint offset = update.mLayer->GetBackgroundLayerOffset();

      ReadbackSink* sink = update.mLayer->GetSink();

      if (!sink) {
        continue;
      }

      if (!aSourceSurface) {
        sink->SetUnknown(update.mSequenceCounter);
        continue;
      }

      RefPtr<DrawTarget> dt = sink->BeginUpdate(update.mUpdateRect + offset,
                                                update.mSequenceCounter);
      if (!dt) {
        continue;
      }

      dt->SetTransform(Matrix::Translation(offset.x, offset.y));

      rotBuffer.DrawBufferWithRotation(dt);

      update.mLayer->GetSink()->EndUpdate(update.mUpdateRect + offset);
    }
  }

 private:
  nsTArray<ReadbackProcessor::Update> mReadbackUpdates;
  // This array is used to keep the layers alive until the callback.
  std::vector<RefPtr<Layer>> mLayerRefs;

  IntRect mBufferRect;
  nsIntPoint mBufferRotation;
};

void ContentClientRemoteBuffer::EndPaint(
    PaintState& aPaintState,
    nsTArray<ReadbackProcessor::Update>* aReadbackUpdates) {
  MOZ_ASSERT(!mBuffer || !mBuffer->HaveBufferOnWhite() || !aReadbackUpdates ||
             aReadbackUpdates->Length() == 0);

  RemoteRotatedBuffer* remoteBuffer = GetRemoteBuffer();

  if (remoteBuffer && remoteBuffer->IsLocked()) {
    if (aReadbackUpdates && aReadbackUpdates->Length() > 0) {
      RefPtr<TextureReadbackSink> readbackSink =
          new RemoteBufferReadbackProcessor(aReadbackUpdates,
                                            remoteBuffer->BufferRect(),
                                            remoteBuffer->BufferRotation());

      remoteBuffer->GetClient()->SetReadbackSink(readbackSink);
    }

    remoteBuffer->Unlock();
    remoteBuffer->SyncWithObject(mForwarder->GetSyncObject());
  }

  ContentClient::EndPaint(aPaintState, aReadbackUpdates);
}

RefPtr<RotatedBuffer> ContentClientRemoteBuffer::CreateBuffer(
    gfxContentType aType, const IntRect& aRect, uint32_t aFlags) {
  // If we hit this assertion, then it might be due to an empty transaction
  // followed by a real transaction. Our buffers should be created (but not
  // painted in the empty transaction) and then painted (but not created) in the
  // real transaction. That is kind of fragile, and this assert will catch
  // circumstances where we screw that up, e.g., by unnecessarily recreating our
  // buffers.
  MOZ_ASSERT(!mIsNewBuffer,
             "Bad! Did we create a buffer twice without painting?");

  gfx::SurfaceFormat format =
      gfxPlatform::GetPlatform()->Optimal2DFormatForContent(aType);

  TextureFlags textureFlags = TextureFlagsForContentClientFlags(aFlags);
  if (aFlags & BUFFER_COMPONENT_ALPHA) {
    textureFlags |= TextureFlags::COMPONENT_ALPHA;
  }

  RefPtr<RotatedBuffer> buffer =
      CreateBufferInternal(aRect, format, textureFlags);

  if (!buffer) {
    return nullptr;
  }

  mIsNewBuffer = true;
  mTextureFlags = textureFlags;

  return buffer;
}

RefPtr<RotatedBuffer> ContentClientRemoteBuffer::CreateBufferInternal(
    const gfx::IntRect& aRect, gfx::SurfaceFormat aFormat,
    TextureFlags aFlags) {
  TextureAllocationFlags textureAllocFlags =
      TextureAllocationFlags::ALLOC_DEFAULT;

  RefPtr<TextureClient> textureClient = CreateTextureClientForDrawing(
      aFormat, aRect.Size(), BackendSelector::Content,
      aFlags | ExtraTextureFlags() | TextureFlags::BLOCKING_READ_LOCK,
      textureAllocFlags);

  if (!textureClient || !AddTextureClient(textureClient)) {
    return nullptr;
  }

  RefPtr<TextureClient> textureClientOnWhite;
  if (aFlags & TextureFlags::COMPONENT_ALPHA) {
    TextureAllocationFlags allocFlags = TextureAllocationFlags::ALLOC_DEFAULT;
    if (mForwarder->SupportsTextureDirectMapping()) {
      allocFlags =
          TextureAllocationFlags(allocFlags | ALLOC_ALLOW_DIRECT_MAPPING);
    }
    textureClientOnWhite =
        textureClient->CreateSimilar(mForwarder->GetCompositorBackendType(),
                                     aFlags | ExtraTextureFlags(), allocFlags);
    if (!textureClientOnWhite || !AddTextureClient(textureClientOnWhite)) {
      return nullptr;
    }
    // We don't enable the readlock for the white buffer since we always
    // use them together and waiting on the lock for the black
    // should be sufficient.
  }

  return new RemoteRotatedBuffer(textureClient, textureClientOnWhite, aRect,
                                 IntPoint(0, 0));
}

nsIntRegion ContentClientRemoteBuffer::GetUpdatedRegion(
    const nsIntRegion& aRegionToDraw, const nsIntRegion& aVisibleRegion) {
  nsIntRegion updatedRegion;
  if (mIsNewBuffer || mBuffer->DidSelfCopy()) {
    // A buffer reallocation clears both buffers. The front buffer has all the
    // content by now, but the back buffer is still clear. Here, in effect, we
    // are saying to copy all of the pixels of the front buffer to the back.
    // Also when we self-copied in the buffer, the buffer space
    // changes and some changed buffer content isn't reflected in the
    // draw or invalidate region (on purpose!).  When this happens, we
    // need to read back the entire buffer too.
    updatedRegion = aVisibleRegion.GetBounds();
    mIsNewBuffer = false;
  } else {
    updatedRegion = aRegionToDraw;
  }

  MOZ_ASSERT(mBuffer, "should have a back buffer by now");
  NS_ASSERTION(mBuffer->BufferRect().Contains(aRegionToDraw.GetBounds()),
               "Update outside of buffer rect!");

  return updatedRegion;
}

void ContentClientRemoteBuffer::Updated(const nsIntRegion& aRegionToDraw,
                                        const nsIntRegion& aVisibleRegion) {
  nsIntRegion updatedRegion = GetUpdatedRegion(aRegionToDraw, aVisibleRegion);

  RemoteRotatedBuffer* remoteBuffer = GetRemoteBuffer();

  MOZ_ASSERT(remoteBuffer && remoteBuffer->GetClient());
  if (remoteBuffer->HaveBufferOnWhite()) {
    mForwarder->UseComponentAlphaTextures(this, remoteBuffer->GetClient(),
                                          remoteBuffer->GetClientOnWhite());
  } else {
    AutoTArray<CompositableForwarder::TimedTextureClient, 1> textures;
    CompositableForwarder::TimedTextureClient* t = textures.AppendElement();
    t->mTextureClient = remoteBuffer->GetClient();
    IntSize size = remoteBuffer->GetClient()->GetSize();
    t->mPictureRect = nsIntRect(0, 0, size.width, size.height);

    GetForwarder()->UseTextures(this, textures);
  }

  // This forces a synchronous transaction, so we can swap buffers now
  // and know that we'll have sole ownership of the old front buffer
  // by the time we paint next.
  mForwarder->UpdateTextureRegion(
      this,
      ThebesBufferData(remoteBuffer->BufferRect(),
                       remoteBuffer->BufferRotation()),
      updatedRegion);
  SwapBuffers(updatedRegion);
}

void ContentClientRemoteBuffer::Dump(std::stringstream& aStream,
                                     const char* aPrefix, bool aDumpHtml,
                                     TextureDumpMode aCompress) {
  RemoteRotatedBuffer* remoteBuffer = GetRemoteBuffer();

  // TODO We should combine the OnWhite/OnBlack here an just output a single
  // image.
  if (!aDumpHtml) {
    aStream << "\n" << aPrefix << "Surface: ";
  }
  CompositableClient::DumpTextureClient(
      aStream, remoteBuffer ? remoteBuffer->GetClient() : nullptr, aCompress);
}

void ContentClientDoubleBuffered::Dump(std::stringstream& aStream,
                                       const char* aPrefix, bool aDumpHtml,
                                       TextureDumpMode aCompress) {
  // TODO We should combine the OnWhite/OnBlack here an just output a single
  // image.
  if (!aDumpHtml) {
    aStream << "\n" << aPrefix << "Surface: ";
  }
  CompositableClient::DumpTextureClient(
      aStream, mFrontBuffer ? mFrontBuffer->GetClient() : nullptr, aCompress);
}

void ContentClientDoubleBuffered::Clear() {
  ContentClient::Clear();
  mFrontBuffer = nullptr;
}

void ContentClientDoubleBuffered::SwapBuffers(
    const nsIntRegion& aFrontUpdatedRegion) {
  mFrontUpdatedRegion = aFrontUpdatedRegion;

  RefPtr<RemoteRotatedBuffer> frontBuffer = mFrontBuffer;
  RefPtr<RemoteRotatedBuffer> backBuffer = GetRemoteBuffer();

  std::swap(frontBuffer, backBuffer);

  mFrontBuffer = frontBuffer;
  mBuffer = backBuffer;

  mFrontAndBackBufferDiffer = true;
}

ContentClient::PaintState ContentClientDoubleBuffered::BeginPaint(
    PaintedLayer* aLayer, uint32_t aFlags) {
  EnsureBackBufferIfFrontBuffer();

  mIsNewBuffer = false;

  if (!mFrontBuffer || !mBuffer) {
    mFrontAndBackBufferDiffer = false;
  }

  if (mFrontAndBackBufferDiffer) {
    if (mFrontBuffer->DidSelfCopy()) {
      // We can't easily draw our front buffer into us, since we're going to be
      // copying stuff around anyway it's easiest if we just move our situation
      // to non-rotated while we're at it. If this situation occurs we'll have
      // hit a self-copy path in PaintThebes before as well anyway.
      gfx::IntRect backBufferRect = mBuffer->BufferRect();
      backBufferRect.MoveTo(mFrontBuffer->BufferRect().TopLeft());

      mBuffer->SetBufferRect(backBufferRect);
      mBuffer->SetBufferRotation(IntPoint(0, 0));
    } else {
      mBuffer->SetBufferRect(mFrontBuffer->BufferRect());
      mBuffer->SetBufferRotation(mFrontBuffer->BufferRotation());
    }
  }

  return ContentClient::BeginPaint(aLayer, aFlags);
}

// Sync front/back buffers content
// After executing, the new back buffer has the same (interesting) pixels as
// the new front buffer, and mValidRegion et al. are correct wrt the new
// back buffer (i.e. as they were for the old back buffer)
void ContentClientDoubleBuffered::FinalizeFrame(PaintState& aPaintState) {
  if (!mFrontAndBackBufferDiffer) {
    MOZ_ASSERT(!mFrontBuffer || !mFrontBuffer->DidSelfCopy(),
               "If the front buffer did a self copy then our front and back "
               "buffer must be different.");
    return;
  }

  MOZ_ASSERT(mFrontBuffer && mBuffer);
  if (!mFrontBuffer || !mBuffer) {
    return;
  }

  MOZ_LAYERS_LOG(
      ("BasicShadowableThebes(%p): reading back <x=%d,y=%d,w=%d,h=%d>", this,
       mFrontUpdatedRegion.GetBounds().X(), mFrontUpdatedRegion.GetBounds().Y(),
       mFrontUpdatedRegion.GetBounds().Width(),
       mFrontUpdatedRegion.GetBounds().Height()));

  mFrontAndBackBufferDiffer = false;

  nsIntRegion updateRegion = mFrontUpdatedRegion;
  if (mFrontBuffer->DidSelfCopy()) {
    mFrontBuffer->ClearDidSelfCopy();
    updateRegion = mBuffer->BufferRect();
  }

  // No point in sync'ing what we are going to draw over anyway. And if there is
  // nothing to sync at all, there is nothing to do and we can go home early.
  updateRegion.Sub(updateRegion, aPaintState.mRegionToDraw);
  if (updateRegion.IsEmpty()) {
    return;
  }

  OpenMode openMode = aPaintState.mAsyncPaint ? OpenMode::OPEN_READ_ASYNC
                                              : OpenMode::OPEN_READ_ONLY;

  if (mFrontBuffer->Lock(openMode)) {
    mBuffer->UpdateDestinationFrom(*mFrontBuffer, updateRegion.GetBounds());

    if (aPaintState.mAsyncPaint) {
      aPaintState.mAsyncTask->mClients.AppendElement(mFrontBuffer->GetClient());
      if (mFrontBuffer->GetClientOnWhite()) {
        aPaintState.mAsyncTask->mClients.AppendElement(
            mFrontBuffer->GetClientOnWhite());
      }
    }

    mFrontBuffer->Unlock();
  }
}

void ContentClientDoubleBuffered::EnsureBackBufferIfFrontBuffer() {
  if (!mBuffer && mFrontBuffer) {
    mBuffer = CreateBufferInternal(mFrontBuffer->BufferRect(),
                                   mFrontBuffer->GetFormat(), mTextureFlags);
    MOZ_ASSERT(mBuffer);
  }
}

}  // namespace layers
}  // namespace mozilla