-
Notifications
You must be signed in to change notification settings - Fork 54
/
DrawTargetD2D1.cpp
2283 lines (1874 loc) · 74.8 KB
/
DrawTargetD2D1.cpp
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- 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 <initguid.h>
#include "DrawTargetD2D1.h"
#include "FilterNodeSoftware.h"
#include "GradientStopsD2D.h"
#include "SourceSurfaceCapture.h"
#include "SourceSurfaceD2D1.h"
#include "SourceSurfaceDual.h"
#include "RadialGradientEffectD2D1.h"
#include "PathCapture.h"
#include "HelpersD2D.h"
#include "FilterNodeD2D1.h"
#include "ExtendInputEffectD2D1.h"
#include "nsAppRunner.h"
#include "MainThreadUtils.h"
#include "mozilla/Mutex.h"
// decltype is not usable for overloaded functions.
typedef HRESULT(WINAPI* D2D1CreateFactoryFunc)(
D2D1_FACTORY_TYPE factoryType, REFIID iid,
CONST D2D1_FACTORY_OPTIONS* pFactoryOptions, void** factory);
namespace mozilla {
namespace gfx {
uint64_t DrawTargetD2D1::mVRAMUsageDT;
uint64_t DrawTargetD2D1::mVRAMUsageSS;
StaticRefPtr<ID2D1Factory1> DrawTargetD2D1::mFactory;
const D2D1_MATRIX_5X4_F kLuminanceMatrix =
D2D1::Matrix5x4F(0, 0, 0, 0.2125f, 0, 0, 0, 0.7154f, 0, 0, 0, 0.0721f, 0, 0,
0, 0, 0, 0, 0, 0);
RefPtr<ID2D1Factory1> D2DFactory() { return DrawTargetD2D1::factory(); }
DrawTargetD2D1::DrawTargetD2D1()
: mPushedLayers(1),
mSnapshotLock(std::make_shared<Mutex>("DrawTargetD2D1::mSnapshotLock")),
mUsedCommandListsSincePurge(0),
mTransformedGlyphsSinceLastPurge(0),
mComplexBlendsWithListInList(0),
mDeviceSeq(0),
mInitState(InitState::Uninitialized) {}
DrawTargetD2D1::~DrawTargetD2D1() {
PopAllClips();
if (mSnapshot) {
MutexAutoLock lock(*mSnapshotLock);
// We may hold the only reference. MarkIndependent will clear mSnapshot;
// keep the snapshot object alive so it doesn't get destroyed while
// MarkIndependent is running.
RefPtr<SourceSurfaceD2D1> deathGrip = mSnapshot;
// mSnapshot can be treated as independent of this DrawTarget since we know
// this DrawTarget won't change again.
deathGrip->MarkIndependent();
// mSnapshot will be cleared now.
}
if (mDC && IsDeviceContextValid()) {
// The only way mDC can be null is if Init failed, but it can happen and the
// destructor is the only place where we need to check for it since the
// DrawTarget will destroyed right after Init fails.
mDC->EndDraw();
}
{
// Until this point in the destructor it -must- still be valid for
// FlushInternal to be called on this.
StaticMutexAutoLock lock(Factory::mDTDependencyLock);
// Targets depending on us can break that dependency, since we're obviously
// not going to be modified in the future.
for (auto iter = mDependentTargets.begin(); iter != mDependentTargets.end();
iter++) {
(*iter)->mDependingOnTargets.erase(this);
}
// Our dependencies on other targets no longer matter.
for (TargetSet::iterator iter = mDependingOnTargets.begin();
iter != mDependingOnTargets.end(); iter++) {
(*iter)->mDependentTargets.erase(this);
}
}
}
bool DrawTargetD2D1::IsValid() const {
if (NS_IsMainThread()) {
// Uninitialized DTs are considered valid.
return mInitState != InitState::Failure;
} else {
return const_cast<DrawTargetD2D1*>(this)->EnsureInitialized();
}
}
already_AddRefed<SourceSurface> DrawTargetD2D1::Snapshot() {
if (!EnsureInitialized()) {
return nullptr;
}
MutexAutoLock lock(*mSnapshotLock);
if (mSnapshot) {
RefPtr<SourceSurface> snapshot(mSnapshot);
return snapshot.forget();
}
PopAllClips();
Flush();
mSnapshot = new SourceSurfaceD2D1(mBitmap, mDC, mFormat, mSize, this);
RefPtr<SourceSurface> snapshot(mSnapshot);
return snapshot.forget();
}
bool DrawTargetD2D1::EnsureLuminanceEffect() {
if (mLuminanceEffect.get()) {
return true;
}
HRESULT hr = mDC->CreateEffect(CLSID_D2D1ColorMatrix,
getter_AddRefs(mLuminanceEffect));
if (FAILED(hr)) {
gfxCriticalError() << "Failed to create luminance effect. Code: "
<< hexa(hr);
return false;
}
mLuminanceEffect->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX,
kLuminanceMatrix);
mLuminanceEffect->SetValue(D2D1_COLORMATRIX_PROP_ALPHA_MODE,
D2D1_COLORMATRIX_ALPHA_MODE_STRAIGHT);
return true;
}
already_AddRefed<SourceSurface> DrawTargetD2D1::IntoLuminanceSource(
LuminanceType aLuminanceType, float aOpacity) {
if (!EnsureInitialized()) {
return nullptr;
}
if ((aLuminanceType != LuminanceType::LUMINANCE) ||
// See bug 1372577, some race condition where we get invalid
// results with D2D in the parent process. Fallback in that case.
XRE_IsParentProcess()) {
return DrawTarget::IntoLuminanceSource(aLuminanceType, aOpacity);
}
// Create the luminance effect
if (!EnsureLuminanceEffect()) {
return DrawTarget::IntoLuminanceSource(aLuminanceType, aOpacity);
}
Flush();
{
D2D1_MATRIX_5X4_F matrix = kLuminanceMatrix;
matrix._14 *= aOpacity;
matrix._24 *= aOpacity;
matrix._34 *= aOpacity;
mLuminanceEffect->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX, matrix);
}
mLuminanceEffect->SetInput(0, mBitmap);
RefPtr<ID2D1Image> luminanceOutput;
mLuminanceEffect->GetOutput(getter_AddRefs(luminanceOutput));
return MakeAndAddRef<SourceSurfaceD2D1>(luminanceOutput, mDC,
SurfaceFormat::B8G8R8A8, mSize);
}
// Command lists are kept around by device contexts until EndDraw is called,
// this can cause issues with memory usage (see bug 1238328). EndDraw/BeginDraw
// are expensive though, especially relatively when little work is done, so
// we try to reduce the amount of times we execute these purges.
static const uint32_t kPushedLayersBeforePurge = 25;
// Rendering glyphs with different transforms causes the glyph cache to grow
// very large (see bug 1474883) so we must call EndDraw every so often.
static const uint32_t kTransformedGlyphsBeforePurge = 1000;
void DrawTargetD2D1::Flush() { FlushInternal(); }
void DrawTargetD2D1::DrawSurface(SourceSurface* aSurface, const Rect& aDest,
const Rect& aSource,
const DrawSurfaceOptions& aSurfOptions,
const DrawOptions& aOptions) {
PrepareForDrawing(aOptions.mCompositionOp, ColorPattern(Color()));
D2D1_RECT_F samplingBounds;
if (aSurfOptions.mSamplingBounds == SamplingBounds::BOUNDED) {
samplingBounds = D2DRect(aSource);
} else {
samplingBounds = D2D1::RectF(0, 0, Float(aSurface->GetSize().width),
Float(aSurface->GetSize().height));
}
Float xScale = aDest.Width() / aSource.Width();
Float yScale = aDest.Height() / aSource.Height();
RefPtr<ID2D1ImageBrush> brush;
// Here we scale the source pattern up to the size and position where we want
// it to be.
Matrix transform;
transform.PreTranslate(aDest.X() - aSource.X() * xScale,
aDest.Y() - aSource.Y() * yScale);
transform.PreScale(xScale, yScale);
RefPtr<ID2D1Image> image =
GetImageForSurface(aSurface, transform, ExtendMode::CLAMP);
if (!image) {
gfxWarning() << *this << ": Unable to get D2D image for surface.";
return;
}
RefPtr<ID2D1Bitmap> bitmap;
HRESULT hr = E_FAIL;
if (aSurface->GetType() == SurfaceType::D2D1_1_IMAGE) {
// If this is called with a DataSourceSurface it might do a partial upload
// that our DrawBitmap call doesn't support.
hr = image->QueryInterface((ID2D1Bitmap**)getter_AddRefs(bitmap));
}
if (SUCCEEDED(hr) && bitmap &&
aSurfOptions.mSamplingBounds == SamplingBounds::UNBOUNDED) {
mDC->DrawBitmap(bitmap, D2DRect(aDest), aOptions.mAlpha,
D2DFilter(aSurfOptions.mSamplingFilter), D2DRect(aSource));
} else {
// This has issues ignoring the alpha channel on windows 7 with images
// marked opaque.
MOZ_ASSERT(aSurface->GetFormat() != SurfaceFormat::B8G8R8X8);
// Bug 1275478 - D2D1 cannot draw A8 surface correctly.
MOZ_ASSERT(aSurface->GetFormat() != SurfaceFormat::A8);
mDC->CreateImageBrush(
image,
D2D1::ImageBrushProperties(
samplingBounds, D2D1_EXTEND_MODE_CLAMP, D2D1_EXTEND_MODE_CLAMP,
D2DInterpolationMode(aSurfOptions.mSamplingFilter)),
D2D1::BrushProperties(aOptions.mAlpha, D2DMatrix(transform)),
getter_AddRefs(brush));
mDC->FillRectangle(D2DRect(aDest), brush);
}
FinalizeDrawing(aOptions.mCompositionOp, ColorPattern(Color()));
}
void DrawTargetD2D1::DrawFilter(FilterNode* aNode, const Rect& aSourceRect,
const Point& aDestPoint,
const DrawOptions& aOptions) {
if (aNode->GetBackendType() != FILTER_BACKEND_DIRECT2D1_1) {
gfxWarning() << *this << ": Incompatible filter passed to DrawFilter.";
return;
}
PrepareForDrawing(aOptions.mCompositionOp, ColorPattern(Color()));
mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
FilterNodeD2D1* node = static_cast<FilterNodeD2D1*>(aNode);
node->WillDraw(this);
if (aOptions.mAlpha == 1.0f) {
mDC->DrawImage(node->OutputEffect(), D2DPoint(aDestPoint),
D2DRect(aSourceRect));
} else {
RefPtr<ID2D1Image> image;
node->OutputEffect()->GetOutput(getter_AddRefs(image));
Matrix mat = Matrix::Translation(aDestPoint);
RefPtr<ID2D1ImageBrush> imageBrush;
mDC->CreateImageBrush(
image, D2D1::ImageBrushProperties(D2DRect(aSourceRect)),
D2D1::BrushProperties(aOptions.mAlpha, D2DMatrix(mat)),
getter_AddRefs(imageBrush));
mDC->FillRectangle(D2D1::RectF(aDestPoint.x, aDestPoint.y,
aDestPoint.x + aSourceRect.width,
aDestPoint.y + aSourceRect.height),
imageBrush);
}
FinalizeDrawing(aOptions.mCompositionOp, ColorPattern(Color()));
}
void DrawTargetD2D1::DrawSurfaceWithShadow(SourceSurface* aSurface,
const Point& aDest,
const Color& aColor,
const Point& aOffset, Float aSigma,
CompositionOp aOperator) {
if (!EnsureInitialized()) {
return;
}
MarkChanged();
mDC->SetTransform(D2D1::IdentityMatrix());
mTransformDirty = true;
Matrix mat;
RefPtr<ID2D1Image> image =
GetImageForSurface(aSurface, mat, ExtendMode::CLAMP, nullptr, false);
if (!image) {
gfxWarning() << "Couldn't get image for surface.";
return;
}
if (!mat.IsIdentity()) {
gfxDebug() << *this
<< ": At this point complex partial uploads are not supported "
"for Shadow surfaces.";
return;
}
// Step 1, create the shadow effect.
RefPtr<ID2D1Effect> shadowEffect;
HRESULT hr = mDC->CreateEffect(
mFormat == SurfaceFormat::A8 ? CLSID_D2D1GaussianBlur : CLSID_D2D1Shadow,
getter_AddRefs(shadowEffect));
if (FAILED(hr) || !shadowEffect) {
gfxWarning() << "Failed to create shadow effect. Code: " << hexa(hr);
return;
}
shadowEffect->SetInput(0, image);
if (mFormat == SurfaceFormat::A8) {
shadowEffect->SetValue(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION, aSigma);
shadowEffect->SetValue(D2D1_GAUSSIANBLUR_PROP_BORDER_MODE,
D2D1_BORDER_MODE_HARD);
} else {
shadowEffect->SetValue(D2D1_SHADOW_PROP_BLUR_STANDARD_DEVIATION, aSigma);
D2D1_VECTOR_4F color = {aColor.r, aColor.g, aColor.b, aColor.a};
shadowEffect->SetValue(D2D1_SHADOW_PROP_COLOR, color);
}
D2D1_POINT_2F shadowPoint = D2DPoint(aDest + aOffset);
mDC->DrawImage(shadowEffect, &shadowPoint, nullptr,
D2D1_INTERPOLATION_MODE_LINEAR, D2DCompositionMode(aOperator));
if (aSurface->GetFormat() != SurfaceFormat::A8) {
D2D1_POINT_2F imgPoint = D2DPoint(aDest);
mDC->DrawImage(image, &imgPoint, nullptr, D2D1_INTERPOLATION_MODE_LINEAR,
D2DCompositionMode(aOperator));
}
}
void DrawTargetD2D1::ClearRect(const Rect& aRect) {
if (!EnsureInitialized()) {
return;
}
if (aRect.IsEmpty()) {
// Nothing to be done.
return;
}
MarkChanged();
PopAllClips();
PushClipRect(aRect);
if (mTransformDirty || !mTransform.IsIdentity()) {
mDC->SetTransform(D2D1::IdentityMatrix());
mTransformDirty = true;
}
D2D1_RECT_F clipRect;
bool isPixelAligned;
if (mTransform.IsRectilinear() &&
GetDeviceSpaceClipRect(clipRect, isPixelAligned)) {
mDC->PushAxisAlignedClip(clipRect, isPixelAligned
? D2D1_ANTIALIAS_MODE_ALIASED
: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
mDC->Clear();
mDC->PopAxisAlignedClip();
PopClip();
return;
}
RefPtr<ID2D1CommandList> list;
mUsedCommandListsSincePurge++;
mDC->CreateCommandList(getter_AddRefs(list));
mDC->SetTarget(list);
IntRect addClipRect;
RefPtr<ID2D1Geometry> geom = GetClippedGeometry(&addClipRect);
RefPtr<ID2D1SolidColorBrush> brush;
mDC->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White),
getter_AddRefs(brush));
mDC->PushAxisAlignedClip(
D2D1::RectF(addClipRect.X(), addClipRect.Y(), addClipRect.XMost(),
addClipRect.YMost()),
D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
mDC->FillGeometry(geom, brush);
mDC->PopAxisAlignedClip();
mDC->SetTarget(CurrentTarget());
list->Close();
mDC->DrawImage(list, D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
D2D1_COMPOSITE_MODE_DESTINATION_OUT);
PopClip();
return;
}
void DrawTargetD2D1::MaskSurface(const Pattern& aSource, SourceSurface* aMask,
Point aOffset, const DrawOptions& aOptions) {
if (!EnsureInitialized()) {
return;
}
MarkChanged();
RefPtr<ID2D1Bitmap> bitmap;
Matrix mat = Matrix::Translation(aOffset);
RefPtr<ID2D1Image> image =
GetImageForSurface(aMask, mat, ExtendMode::CLAMP, nullptr);
MOZ_ASSERT(!mat.HasNonTranslation());
aOffset.x = mat._31;
aOffset.y = mat._32;
if (!image) {
gfxWarning() << "Failed to get image for surface.";
return;
}
PrepareForDrawing(aOptions.mCompositionOp, aSource);
IntSize size =
IntSize::Truncate(aMask->GetSize().width, aMask->GetSize().height);
Rect dest =
Rect(aOffset.x + aMask->GetRect().x, aOffset.y + aMask->GetRect().y,
Float(size.width), Float(size.height));
HRESULT hr = image->QueryInterface((ID2D1Bitmap**)getter_AddRefs(bitmap));
if (!bitmap || FAILED(hr)) {
// D2D says if we have an actual ID2D1Image and not a bitmap underlying the
// object, we can't query for a bitmap. Instead, Push/PopLayer
gfxWarning() << "FillOpacityMask only works with Bitmap source surfaces. "
"Falling back to push/pop layer";
RefPtr<ID2D1Brush> source = CreateBrushForPattern(aSource, aOptions.mAlpha);
RefPtr<ID2D1ImageBrush> maskBrush;
hr = mDC->CreateImageBrush(
image,
D2D1::ImageBrushProperties(D2D1::RectF(0, 0, size.width, size.height)),
D2D1::BrushProperties(
1.0f, D2D1::Matrix3x2F::Translation(aMask->GetRect().x,
aMask->GetRect().y)),
getter_AddRefs(maskBrush));
MOZ_ASSERT(SUCCEEDED(hr));
mDC->PushLayer(
D2D1::LayerParameters1(D2D1::InfiniteRect(), nullptr,
D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
D2D1::Matrix3x2F::Translation(
aMask->GetRect().x, aMask->GetRect().y),
1.0f, maskBrush, D2D1_LAYER_OPTIONS1_NONE),
nullptr);
mDC->FillRectangle(D2DRect(dest), source);
mDC->PopLayer();
FinalizeDrawing(aOptions.mCompositionOp, aSource);
return;
} else {
// If this is a data source surface, we might have created a partial bitmap
// for this surface and only uploaded part of the mask. In that case,
// we have to fixup our sizes here.
size.width = bitmap->GetSize().width;
size.height = bitmap->GetSize().height;
dest.SetWidth(size.width);
dest.SetHeight(size.height);
}
// FillOpacityMask only works if the antialias mode is MODE_ALIASED
mDC->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);
Rect maskRect = Rect(aMask->GetRect().x, aMask->GetRect().y,
Float(size.width), Float(size.height));
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aSource, aOptions.mAlpha);
mDC->FillOpacityMask(bitmap, brush, D2D1_OPACITY_MASK_CONTENT_GRAPHICS,
D2DRect(dest), D2DRect(maskRect));
mDC->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
FinalizeDrawing(aOptions.mCompositionOp, aSource);
}
void DrawTargetD2D1::CopySurface(SourceSurface* aSurface,
const IntRect& aSourceRect,
const IntPoint& aDestination) {
if (!EnsureInitialized()) {
return;
}
MarkChanged();
PopAllClips();
mDC->SetTransform(D2D1::IdentityMatrix());
mTransformDirty = true;
Matrix mat = Matrix::Translation(aDestination.x - aSourceRect.X(),
aDestination.y - aSourceRect.Y());
RefPtr<ID2D1Image> image =
GetImageForSurface(aSurface, mat, ExtendMode::CLAMP, nullptr, false);
if (!image) {
gfxWarning() << "Couldn't get image for surface.";
return;
}
if (mat.HasNonIntegerTranslation()) {
gfxDebug() << *this
<< ": At this point scaled partial uploads are not supported "
"for CopySurface.";
return;
}
IntRect sourceRect = aSourceRect;
sourceRect.SetLeftEdge(sourceRect.X() + (aDestination.x - aSourceRect.X()) -
mat._31);
sourceRect.SetTopEdge(sourceRect.Y() + (aDestination.y - aSourceRect.Y()) -
mat._32);
RefPtr<ID2D1Bitmap> bitmap;
HRESULT hr = image->QueryInterface((ID2D1Bitmap**)getter_AddRefs(bitmap));
if (SUCCEEDED(hr) && bitmap && mFormat == SurfaceFormat::A8) {
RefPtr<ID2D1SolidColorBrush> brush;
mDC->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White),
D2D1::BrushProperties(), getter_AddRefs(brush));
mDC->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);
mDC->SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND_COPY);
mDC->FillOpacityMask(bitmap, brush, D2D1_OPACITY_MASK_CONTENT_GRAPHICS);
mDC->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
mDC->SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND_SOURCE_OVER);
return;
}
Rect srcRect(Float(sourceRect.X()), Float(sourceRect.Y()),
Float(aSourceRect.Width()), Float(aSourceRect.Height()));
Rect dstRect(Float(aDestination.x), Float(aDestination.y),
Float(aSourceRect.Width()), Float(aSourceRect.Height()));
if (SUCCEEDED(hr) && bitmap) {
mDC->SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND_COPY);
mDC->DrawBitmap(bitmap, D2DRect(dstRect), 1.0f,
D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
D2DRect(srcRect));
mDC->SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND_SOURCE_OVER);
return;
}
mDC->DrawImage(image,
D2D1::Point2F(Float(aDestination.x), Float(aDestination.y)),
D2DRect(srcRect), D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
D2D1_COMPOSITE_MODE_BOUNDED_SOURCE_COPY);
}
void DrawTargetD2D1::FillRect(const Rect& aRect, const Pattern& aPattern,
const DrawOptions& aOptions) {
PrepareForDrawing(aOptions.mCompositionOp, aPattern);
mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aPattern, aOptions.mAlpha);
mDC->FillRectangle(D2DRect(aRect), brush);
FinalizeDrawing(aOptions.mCompositionOp, aPattern);
}
void DrawTargetD2D1::FillRoundedRect(const RoundedRect& aRect,
const Pattern& aPattern,
const DrawOptions& aOptions) {
if (!aRect.corners.AreRadiiSame()) {
return DrawTarget::FillRoundedRect(aRect, aPattern, aOptions);
}
PrepareForDrawing(aOptions.mCompositionOp, aPattern);
mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aPattern, aOptions.mAlpha);
mDC->FillRoundedRectangle(D2DRoundedRect(aRect), brush);
FinalizeDrawing(aOptions.mCompositionOp, aPattern);
}
void DrawTargetD2D1::StrokeRect(const Rect& aRect, const Pattern& aPattern,
const StrokeOptions& aStrokeOptions,
const DrawOptions& aOptions) {
PrepareForDrawing(aOptions.mCompositionOp, aPattern);
mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aPattern, aOptions.mAlpha);
RefPtr<ID2D1StrokeStyle> strokeStyle =
CreateStrokeStyleForOptions(aStrokeOptions);
mDC->DrawRectangle(D2DRect(aRect), brush, aStrokeOptions.mLineWidth,
strokeStyle);
FinalizeDrawing(aOptions.mCompositionOp, aPattern);
}
void DrawTargetD2D1::StrokeLine(const Point& aStart, const Point& aEnd,
const Pattern& aPattern,
const StrokeOptions& aStrokeOptions,
const DrawOptions& aOptions) {
PrepareForDrawing(aOptions.mCompositionOp, aPattern);
mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aPattern, aOptions.mAlpha);
RefPtr<ID2D1StrokeStyle> strokeStyle =
CreateStrokeStyleForOptions(aStrokeOptions);
mDC->DrawLine(D2DPoint(aStart), D2DPoint(aEnd), brush,
aStrokeOptions.mLineWidth, strokeStyle);
FinalizeDrawing(aOptions.mCompositionOp, aPattern);
}
void DrawTargetD2D1::Stroke(const Path* aPath, const Pattern& aPattern,
const StrokeOptions& aStrokeOptions,
const DrawOptions& aOptions) {
const Path* path = aPath;
if (aPath->GetBackendType() == BackendType::CAPTURE) {
path = static_cast<const PathCapture*>(aPath)->GetRealizedPath();
}
if (path->GetBackendType() != BackendType::DIRECT2D1_1) {
gfxDebug() << *this << ": Ignoring drawing call for incompatible path.";
return;
}
const PathD2D* d2dPath = static_cast<const PathD2D*>(path);
PrepareForDrawing(aOptions.mCompositionOp, aPattern);
mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aPattern, aOptions.mAlpha);
RefPtr<ID2D1StrokeStyle> strokeStyle =
CreateStrokeStyleForOptions(aStrokeOptions);
mDC->DrawGeometry(d2dPath->mGeometry, brush, aStrokeOptions.mLineWidth,
strokeStyle);
FinalizeDrawing(aOptions.mCompositionOp, aPattern);
}
void DrawTargetD2D1::Fill(const Path* aPath, const Pattern& aPattern,
const DrawOptions& aOptions) {
const Path* path = aPath;
if (aPath && aPath->GetBackendType() == BackendType::CAPTURE) {
path = static_cast<const PathCapture*>(aPath)->GetRealizedPath();
}
if (!path || path->GetBackendType() != BackendType::DIRECT2D1_1) {
gfxDebug() << *this << ": Ignoring drawing call for incompatible path.";
return;
}
const PathD2D* d2dPath = static_cast<const PathD2D*>(path);
PrepareForDrawing(aOptions.mCompositionOp, aPattern);
mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aPattern, aOptions.mAlpha);
mDC->FillGeometry(d2dPath->mGeometry, brush);
FinalizeDrawing(aOptions.mCompositionOp, aPattern);
}
void DrawTargetD2D1::FillGlyphs(ScaledFont* aFont, const GlyphBuffer& aBuffer,
const Pattern& aPattern,
const DrawOptions& aOptions) {
if (aFont->GetType() != FontType::DWRITE) {
gfxDebug() << *this << ": Ignoring drawing call for incompatible font.";
return;
}
ScaledFontDWrite* font = static_cast<ScaledFontDWrite*>(aFont);
IDWriteRenderingParams* params = font->mParams;
AntialiasMode aaMode = font->GetDefaultAAMode();
if (aOptions.mAntialiasMode != AntialiasMode::DEFAULT) {
aaMode = aOptions.mAntialiasMode;
}
PrepareForDrawing(aOptions.mCompositionOp, aPattern);
bool forceClearType = false;
if (!CurrentLayer().mIsOpaque && mPermitSubpixelAA &&
aOptions.mCompositionOp == CompositionOp::OP_OVER &&
aaMode == AntialiasMode::SUBPIXEL) {
forceClearType = true;
}
D2D1_TEXT_ANTIALIAS_MODE d2dAAMode = D2D1_TEXT_ANTIALIAS_MODE_DEFAULT;
switch (aaMode) {
case AntialiasMode::NONE:
d2dAAMode = D2D1_TEXT_ANTIALIAS_MODE_ALIASED;
break;
case AntialiasMode::GRAY:
d2dAAMode = D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE;
break;
case AntialiasMode::SUBPIXEL:
d2dAAMode = D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE;
break;
default:
d2dAAMode = D2D1_TEXT_ANTIALIAS_MODE_DEFAULT;
}
if (d2dAAMode == D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE &&
!CurrentLayer().mIsOpaque && !forceClearType) {
d2dAAMode = D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE;
}
mDC->SetTextAntialiasMode(d2dAAMode);
if (params != mTextRenderingParams) {
mDC->SetTextRenderingParams(params);
mTextRenderingParams = params;
}
RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aPattern, aOptions.mAlpha);
AutoDWriteGlyphRun autoRun;
DWriteGlyphRunFromGlyphs(aBuffer, font, &autoRun);
bool needsRepushedLayers = false;
if (forceClearType) {
D2D1_RECT_F rect;
bool isAligned;
needsRepushedLayers = CurrentLayer().mPushedClips.size() &&
!GetDeviceSpaceClipRect(rect, isAligned);
// If we have a complex clip in our stack and we have a transparent
// background, and subpixel AA is permitted, we need to repush our layer
// stack limited by the glyph run bounds initializing our layers for
// subpixel AA.
if (needsRepushedLayers) {
mDC->GetGlyphRunWorldBounds(D2D1::Point2F(), &autoRun,
DWRITE_MEASURING_MODE_NATURAL, &rect);
rect.left = std::floor(rect.left);
rect.right = std::ceil(rect.right);
rect.top = std::floor(rect.top);
rect.bottom = std::ceil(rect.bottom);
PopAllClips();
if (!mTransform.IsRectilinear()) {
// We must limit the pixels we touch to the -user space- bounds of
// the glyphs being drawn. In order not to get transparent pixels
// copied up in our pushed layer stack.
D2D1_RECT_F userRect;
mDC->SetTransform(D2D1::IdentityMatrix());
mDC->GetGlyphRunWorldBounds(D2D1::Point2F(), &autoRun,
DWRITE_MEASURING_MODE_NATURAL, &userRect);
RefPtr<ID2D1PathGeometry> path;
factory()->CreatePathGeometry(getter_AddRefs(path));
RefPtr<ID2D1GeometrySink> sink;
path->Open(getter_AddRefs(sink));
AddRectToSink(sink, userRect);
sink->Close();
mDC->PushLayer(
D2D1::LayerParameters1(
D2D1::InfiniteRect(), path, D2D1_ANTIALIAS_MODE_ALIASED,
D2DMatrix(mTransform), 1.0f, nullptr,
D2D1_LAYER_OPTIONS1_INITIALIZE_FROM_BACKGROUND |
D2D1_LAYER_OPTIONS1_IGNORE_ALPHA),
nullptr);
}
PushClipsToDC(mDC, true, rect);
mDC->SetTransform(D2DMatrix(mTransform));
}
}
if (brush) {
mDC->DrawGlyphRun(D2D1::Point2F(), &autoRun, brush);
}
if (mTransform.HasNonTranslation()) {
mTransformedGlyphsSinceLastPurge += aBuffer.mNumGlyphs;
}
if (needsRepushedLayers) {
PopClipsFromDC(mDC);
if (!mTransform.IsRectilinear()) {
mDC->PopLayer();
}
}
FinalizeDrawing(aOptions.mCompositionOp, aPattern);
}
void DrawTargetD2D1::Mask(const Pattern& aSource, const Pattern& aMask,
const DrawOptions& aOptions) {
PrepareForDrawing(aOptions.mCompositionOp, aSource);
RefPtr<ID2D1Brush> source = CreateBrushForPattern(aSource, aOptions.mAlpha);
RefPtr<ID2D1Brush> mask = CreateBrushForPattern(aMask, 1.0f);
mDC->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), nullptr,
D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
D2D1::IdentityMatrix(), 1.0f, mask),
nullptr);
Rect rect(0, 0, (Float)mSize.width, (Float)mSize.height);
Matrix mat = mTransform;
mat.Invert();
mDC->FillRectangle(D2DRect(mat.TransformBounds(rect)), source);
mDC->PopLayer();
FinalizeDrawing(aOptions.mCompositionOp, aSource);
}
void DrawTargetD2D1::PushClipGeometry(ID2D1Geometry* aGeometry,
const D2D1_MATRIX_3X2_F& aTransform,
bool aPixelAligned) {
mCurrentClippedGeometry = nullptr;
PushedClip clip;
clip.mGeometry = aGeometry;
clip.mTransform = aTransform;
clip.mIsPixelAligned = aPixelAligned;
aGeometry->GetBounds(aTransform, &clip.mBounds);
CurrentLayer().mPushedClips.push_back(clip);
// The transform of clips is relative to the world matrix, since we use the
// total transform for the clips, make the world matrix identity.
mDC->SetTransform(D2D1::IdentityMatrix());
mTransformDirty = true;
if (CurrentLayer().mClipsArePushed) {
PushD2DLayer(mDC, clip.mGeometry, clip.mTransform, clip.mIsPixelAligned);
}
}
void DrawTargetD2D1::PushClip(const Path* aPath) {
const Path* path = aPath;
if (aPath->GetBackendType() == BackendType::CAPTURE) {
path = static_cast<const PathCapture*>(aPath)->GetRealizedPath();
}
if (path->GetBackendType() != BackendType::DIRECT2D1_1) {
gfxDebug() << *this << ": Ignoring clipping call for incompatible path.";
return;
}
if (!EnsureInitialized()) {
return;
}
RefPtr<PathD2D> pathD2D = static_cast<PathD2D*>(const_cast<Path*>(path));
PushClipGeometry(pathD2D->GetGeometry(), D2DMatrix(mTransform));
}
void DrawTargetD2D1::PushClipRect(const Rect& aRect) {
if (!EnsureInitialized()) {
return;
}
if (!mTransform.IsRectilinear()) {
// Whoops, this isn't a rectangle in device space, Direct2D will not deal
// with this transform the way we want it to.
// See remarks:
// http://msdn.microsoft.com/en-us/library/dd316860%28VS.85%29.aspx
RefPtr<ID2D1Geometry> geom = ConvertRectToGeometry(D2DRect(aRect));
return PushClipGeometry(geom, D2DMatrix(mTransform));
}
mCurrentClippedGeometry = nullptr;
PushedClip clip;
Rect rect = mTransform.TransformBounds(aRect);
IntRect intRect;
clip.mIsPixelAligned = rect.ToIntRect(&intRect);
// Do not store the transform, just store the device space rectangle directly.
clip.mBounds = D2DRect(rect);
CurrentLayer().mPushedClips.push_back(clip);
mDC->SetTransform(D2D1::IdentityMatrix());
mTransformDirty = true;
if (CurrentLayer().mClipsArePushed) {
mDC->PushAxisAlignedClip(
clip.mBounds, clip.mIsPixelAligned ? D2D1_ANTIALIAS_MODE_ALIASED
: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
}
}
void DrawTargetD2D1::PushDeviceSpaceClipRects(const IntRect* aRects,
uint32_t aCount) {
if (!EnsureInitialized()) {
return;
}
// Build a path for the union of the rects.
RefPtr<ID2D1PathGeometry> path;
factory()->CreatePathGeometry(getter_AddRefs(path));
RefPtr<ID2D1GeometrySink> sink;
path->Open(getter_AddRefs(sink));
sink->SetFillMode(D2D1_FILL_MODE_WINDING);
for (uint32_t i = 0; i < aCount; i++) {
const IntRect& rect = aRects[i];
sink->BeginFigure(D2DPoint(rect.TopLeft()), D2D1_FIGURE_BEGIN_FILLED);
D2D1_POINT_2F lines[3] = {D2DPoint(rect.TopRight()),
D2DPoint(rect.BottomRight()),
D2DPoint(rect.BottomLeft())};
sink->AddLines(lines, 3);
sink->EndFigure(D2D1_FIGURE_END_CLOSED);
}
sink->Close();
// The path is in device-space, so there is no transform needed,
// and all rects are pixel aligned.
PushClipGeometry(path, D2D1::IdentityMatrix(), true);
}
void DrawTargetD2D1::PopClip() {
if (!EnsureInitialized()) {
return;
}
mCurrentClippedGeometry = nullptr;
if (CurrentLayer().mPushedClips.empty()) {
gfxDevCrash(LogReason::UnbalancedClipStack)
<< "DrawTargetD2D1::PopClip: No clip to pop.";
return;
}
if (CurrentLayer().mClipsArePushed) {
if (CurrentLayer().mPushedClips.back().mGeometry) {
mDC->PopLayer();
} else {
mDC->PopAxisAlignedClip();
}
}
CurrentLayer().mPushedClips.pop_back();
}
void DrawTargetD2D1::PushLayer(bool aOpaque, Float aOpacity,
SourceSurface* aMask,
const Matrix& aMaskTransform,
const IntRect& aBounds, bool aCopyBackground) {
if (!EnsureInitialized()) {
return;
}
D2D1_LAYER_OPTIONS1 options = D2D1_LAYER_OPTIONS1_NONE;
if (aOpaque) {
options |= D2D1_LAYER_OPTIONS1_IGNORE_ALPHA;
}
if (aCopyBackground) {
options |= D2D1_LAYER_OPTIONS1_INITIALIZE_FROM_BACKGROUND;
}
RefPtr<ID2D1ImageBrush> mask;
Matrix maskTransform = aMaskTransform;
RefPtr<ID2D1PathGeometry> clip;
if (aMask) {
RefPtr<ID2D1Image> image =
GetImageForSurface(aMask, maskTransform, ExtendMode::CLAMP);
mDC->SetTransform(D2D1::IdentityMatrix());
mTransformDirty = true;
maskTransform =
maskTransform.PreTranslate(aMask->GetRect().X(), aMask->GetRect().Y());
// The mask is given in user space. Our layer will apply it in device space.
maskTransform = maskTransform * mTransform;
if (image) {
IntSize maskSize = aMask->GetSize();