This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCanvasRenderingContext2D.cpp
4635 lines (3892 loc) · 135 KB
/
CanvasRenderingContext2D.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: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* 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 "CanvasRenderingContext2D.h"
#include "nsXULElement.h"
#include "nsIServiceManager.h"
#include "nsMathUtils.h"
#include "nsContentUtils.h"
#include "nsIDocument.h"
#include "mozilla/dom/HTMLCanvasElement.h"
#include "nsSVGEffects.h"
#include "nsPresContext.h"
#include "nsIPresShell.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIFrame.h"
#include "nsError.h"
#include "nsCSSParser.h"
#include "mozilla/css/StyleRule.h"
#include "mozilla/css/Declaration.h"
#include "nsComputedDOMStyle.h"
#include "nsStyleSet.h"
#include "nsPrintfCString.h"
#include "nsReadableUtils.h"
#include "nsColor.h"
#include "nsGfxCIID.h"
#include "nsIDocShell.h"
#include "nsIDOMWindow.h"
#include "nsPIDOMWindow.h"
#include "nsDisplayList.h"
#include "nsFocusManager.h"
#include "nsTArray.h"
#include "ImageEncoder.h"
#include "gfxContext.h"
#include "gfxASurface.h"
#include "gfxImageSurface.h"
#include "gfxPlatform.h"
#include "gfxFont.h"
#include "gfxBlur.h"
#include "gfxUtils.h"
#include "nsFrameLoader.h"
#include "nsBidi.h"
#include "nsBidiPresUtils.h"
#include "Layers.h"
#include "CanvasUtils.h"
#include "nsIMemoryReporter.h"
#include "nsStyleUtil.h"
#include "CanvasImageCache.h"
#include <algorithm>
#include "jsapi.h"
#include "jsfriendapi.h"
#include "mozilla/Alignment.h"
#include "mozilla/Assertions.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ImageData.h"
#include "mozilla/dom/PBrowserParent.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/TypedArray.h"
#include "mozilla/Endian.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/PathHelpers.h"
#include "mozilla/gfx/DataSurfaceHelpers.h"
#include "mozilla/ipc/DocumentRendererParent.h"
#include "mozilla/ipc/PDocumentRendererParent.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Preferences.h"
#include "mozilla/Telemetry.h"
#include "mozilla/unused.h"
#include "nsCCUncollectableMarker.h"
#include "nsWrapperCacheInlines.h"
#include "mozilla/dom/CanvasRenderingContext2DBinding.h"
#include "mozilla/dom/HTMLImageElement.h"
#include "mozilla/dom/HTMLVideoElement.h"
#include "mozilla/dom/TextMetrics.h"
#include "mozilla/dom/UnionTypes.h"
#include "mozilla/dom/SVGMatrix.h"
#include "nsGlobalWindow.h"
#include "GLContext.h"
#include "GLContextProvider.h"
#include "SVGContentUtils.h"
#include "nsIScreenManager.h"
#undef free // apparently defined by some windows header, clashing with a free()
// method in SkTypes.h
#ifdef USE_SKIA
#include "SkiaGLGlue.h"
#include "SurfaceStream.h"
#include "SurfaceTypes.h"
#endif
using mozilla::gl::GLContext;
using mozilla::gl::SkiaGLGlue;
using mozilla::gl::GLContextProvider;
#ifdef XP_WIN
#include "gfxWindowsPlatform.h"
#endif
#ifdef MOZ_WIDGET_GONK
#include "mozilla/layers/ShadowLayers.h"
#endif
// windows.h (included by chromium code) defines this, in its infinite wisdom
#undef DrawText
using namespace mozilla;
using namespace mozilla::CanvasUtils;
using namespace mozilla::css;
using namespace mozilla::gfx;
using namespace mozilla::ipc;
using namespace mozilla::layers;
namespace mgfx = mozilla::gfx;
namespace mozilla {
namespace dom {
// Cap sigma to avoid overly large temp surfaces.
const Float SIGMA_MAX = 100;
/* Memory reporter stuff */
static int64_t gCanvasAzureMemoryUsed = 0;
// This is KIND_OTHER because it's not always clear where in memory the pixels
// of a canvas are stored. Furthermore, this memory will be tracked by the
// underlying surface implementations. See bug 655638 for details.
class Canvas2dPixelsReporter MOZ_FINAL : public nsIMemoryReporter
{
~Canvas2dPixelsReporter() {}
public:
NS_DECL_ISUPPORTS
NS_IMETHOD CollectReports(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, bool aAnonymize)
{
return MOZ_COLLECT_REPORT(
"canvas-2d-pixels", KIND_OTHER, UNITS_BYTES,
gCanvasAzureMemoryUsed,
"Memory used by 2D canvases. Each canvas requires "
"(width * height * 4) bytes.");
}
};
NS_IMPL_ISUPPORTS(Canvas2dPixelsReporter, nsIMemoryReporter)
class CanvasRadialGradient : public CanvasGradient
{
public:
CanvasRadialGradient(CanvasRenderingContext2D* aContext,
const Point &aBeginOrigin, Float aBeginRadius,
const Point &aEndOrigin, Float aEndRadius)
: CanvasGradient(aContext, Type::RADIAL)
, mCenter1(aBeginOrigin)
, mCenter2(aEndOrigin)
, mRadius1(aBeginRadius)
, mRadius2(aEndRadius)
{
}
Point mCenter1;
Point mCenter2;
Float mRadius1;
Float mRadius2;
};
class CanvasLinearGradient : public CanvasGradient
{
public:
CanvasLinearGradient(CanvasRenderingContext2D* aContext,
const Point &aBegin, const Point &aEnd)
: CanvasGradient(aContext, Type::LINEAR)
, mBegin(aBegin)
, mEnd(aEnd)
{
}
protected:
friend class CanvasGeneralPattern;
// Beginning of linear gradient.
Point mBegin;
// End of linear gradient.
Point mEnd;
};
// This class is named 'GeneralCanvasPattern' instead of just
// 'GeneralPattern' to keep Windows PGO builds from confusing the
// GeneralPattern class in gfxContext.cpp with this one.
class CanvasGeneralPattern
{
public:
typedef CanvasRenderingContext2D::Style Style;
typedef CanvasRenderingContext2D::ContextState ContextState;
CanvasGeneralPattern() : mPattern(nullptr) {}
~CanvasGeneralPattern()
{
if (mPattern) {
mPattern->~Pattern();
}
}
Pattern& ForStyle(CanvasRenderingContext2D *aCtx,
Style aStyle,
DrawTarget *aRT)
{
// This should only be called once or the mPattern destructor will
// not be executed.
NS_ASSERTION(!mPattern, "ForStyle() should only be called once on CanvasGeneralPattern!");
const ContextState &state = aCtx->CurrentState();
if (state.StyleIsColor(aStyle)) {
mPattern = new (mColorPattern.addr()) ColorPattern(Color::FromABGR(state.colorStyles[aStyle]));
} else if (state.gradientStyles[aStyle] &&
state.gradientStyles[aStyle]->GetType() == CanvasGradient::Type::LINEAR) {
CanvasLinearGradient *gradient =
static_cast<CanvasLinearGradient*>(state.gradientStyles[aStyle].get());
mPattern = new (mLinearGradientPattern.addr())
LinearGradientPattern(gradient->mBegin, gradient->mEnd,
gradient->GetGradientStopsForTarget(aRT));
} else if (state.gradientStyles[aStyle] &&
state.gradientStyles[aStyle]->GetType() == CanvasGradient::Type::RADIAL) {
CanvasRadialGradient *gradient =
static_cast<CanvasRadialGradient*>(state.gradientStyles[aStyle].get());
mPattern = new (mRadialGradientPattern.addr())
RadialGradientPattern(gradient->mCenter1, gradient->mCenter2, gradient->mRadius1,
gradient->mRadius2, gradient->GetGradientStopsForTarget(aRT));
} else if (state.patternStyles[aStyle]) {
if (aCtx->mCanvasElement) {
CanvasUtils::DoDrawImageSecurityCheck(aCtx->mCanvasElement,
state.patternStyles[aStyle]->mPrincipal,
state.patternStyles[aStyle]->mForceWriteOnly,
state.patternStyles[aStyle]->mCORSUsed);
}
ExtendMode mode;
if (state.patternStyles[aStyle]->mRepeat == CanvasPattern::RepeatMode::NOREPEAT) {
mode = ExtendMode::CLAMP;
} else {
mode = ExtendMode::REPEAT;
}
mPattern = new (mSurfacePattern.addr())
SurfacePattern(state.patternStyles[aStyle]->mSurface, mode,
state.patternStyles[aStyle]->mTransform);
}
return *mPattern;
}
union {
AlignedStorage2<ColorPattern> mColorPattern;
AlignedStorage2<LinearGradientPattern> mLinearGradientPattern;
AlignedStorage2<RadialGradientPattern> mRadialGradientPattern;
AlignedStorage2<SurfacePattern> mSurfacePattern;
};
Pattern *mPattern;
};
/* This is an RAII based class that can be used as a drawtarget for
* operations that need a shadow drawn. It will automatically provide a
* temporary target when needed, and if so blend it back with a shadow.
*
* aBounds specifies the bounds of the drawing operation that will be
* drawn to the target, it is given in device space! This function will
* change aBounds to incorporate shadow bounds. If this is nullptr the drawing
* operation will be assumed to cover an infinite rect.
*/
class AdjustedTarget
{
public:
typedef CanvasRenderingContext2D::ContextState ContextState;
AdjustedTarget(CanvasRenderingContext2D *ctx,
mgfx::Rect *aBounds = nullptr)
: mCtx(nullptr)
{
if (!ctx->NeedToDrawShadow()) {
mTarget = ctx->mTarget;
return;
}
mCtx = ctx;
const ContextState &state = mCtx->CurrentState();
mSigma = state.shadowBlur / 2.0f;
if (mSigma > SIGMA_MAX) {
mSigma = SIGMA_MAX;
}
Matrix transform = mCtx->mTarget->GetTransform();
mTempRect = mgfx::Rect(0, 0, ctx->mWidth, ctx->mHeight);
static const gfxFloat GAUSSIAN_SCALE_FACTOR = (3 * sqrt(2 * M_PI) / 4) * 1.5;
int32_t blurRadius = (int32_t) floor(mSigma * GAUSSIAN_SCALE_FACTOR + 0.5);
// We need to enlarge and possibly offset our temporary surface
// so that things outside of the canvas may cast shadows.
mTempRect.Inflate(Margin(blurRadius + std::max<Float>(state.shadowOffset.y, 0),
blurRadius + std::max<Float>(-state.shadowOffset.x, 0),
blurRadius + std::max<Float>(-state.shadowOffset.y, 0),
blurRadius + std::max<Float>(state.shadowOffset.x, 0)));
if (aBounds) {
// We actually include the bounds of the shadow blur, this makes it
// easier to execute the actual blur on hardware, and shouldn't affect
// the amount of pixels that need to be touched.
aBounds->Inflate(Margin(blurRadius, blurRadius,
blurRadius, blurRadius));
mTempRect = mTempRect.Intersect(*aBounds);
}
mTempRect.ScaleRoundOut(1.0f);
transform._31 -= mTempRect.x;
transform._32 -= mTempRect.y;
mTarget =
mCtx->mTarget->CreateShadowDrawTarget(IntSize(int32_t(mTempRect.width), int32_t(mTempRect.height)),
SurfaceFormat::B8G8R8A8, mSigma);
if (!mTarget) {
// XXX - Deal with the situation where our temp size is too big to
// fit in a texture.
mTarget = ctx->mTarget;
mCtx = nullptr;
} else {
mTarget->SetTransform(transform);
}
}
~AdjustedTarget()
{
if (!mCtx) {
return;
}
RefPtr<SourceSurface> snapshot = mTarget->Snapshot();
mCtx->mTarget->DrawSurfaceWithShadow(snapshot, mTempRect.TopLeft(),
Color::FromABGR(mCtx->CurrentState().shadowColor),
mCtx->CurrentState().shadowOffset, mSigma,
mCtx->CurrentState().op);
}
operator DrawTarget*()
{
return mTarget;
}
DrawTarget* operator->()
{
return mTarget;
}
private:
RefPtr<DrawTarget> mTarget;
CanvasRenderingContext2D *mCtx;
Float mSigma;
mgfx::Rect mTempRect;
};
void
CanvasPattern::SetTransform(SVGMatrix& aMatrix)
{
mTransform = ToMatrix(aMatrix.GetMatrix());
}
void
CanvasGradient::AddColorStop(float offset, const nsAString& colorstr, ErrorResult& rv)
{
if (offset < 0.0 || offset > 1.0) {
rv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return;
}
nsCSSValue value;
nsCSSParser parser;
if (!parser.ParseColorString(colorstr, nullptr, 0, value)) {
rv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return;
}
nscolor color;
if (!nsRuleNode::ComputeColor(value, nullptr, nullptr, color)) {
rv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return;
}
mStops = nullptr;
GradientStop newStop;
newStop.offset = offset;
newStop.color = Color::FromABGR(color);
mRawStops.AppendElement(newStop);
}
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(CanvasGradient, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(CanvasGradient, Release)
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(CanvasGradient, mContext)
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(CanvasPattern, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(CanvasPattern, Release)
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(CanvasPattern, mContext)
class CanvasRenderingContext2DUserData : public LayerUserData {
public:
CanvasRenderingContext2DUserData(CanvasRenderingContext2D *aContext)
: mContext(aContext)
{
aContext->mUserDatas.AppendElement(this);
}
~CanvasRenderingContext2DUserData()
{
if (mContext) {
mContext->mUserDatas.RemoveElement(this);
}
}
static void PreTransactionCallback(void* aData)
{
CanvasRenderingContext2DUserData* self =
static_cast<CanvasRenderingContext2DUserData*>(aData);
CanvasRenderingContext2D* context = self->mContext;
if (!context || !context->mStream || !context->mTarget)
return;
// Since SkiaGL default to store drawing command until flush
// We will have to flush it before present.
context->mTarget->Flush();
}
static void DidTransactionCallback(void* aData)
{
CanvasRenderingContext2DUserData* self =
static_cast<CanvasRenderingContext2DUserData*>(aData);
if (self->mContext) {
self->mContext->MarkContextClean();
}
}
bool IsForContext(CanvasRenderingContext2D *aContext)
{
return mContext == aContext;
}
void Forget()
{
mContext = nullptr;
}
private:
CanvasRenderingContext2D *mContext;
};
NS_IMPL_CYCLE_COLLECTING_ADDREF(CanvasRenderingContext2D)
NS_IMPL_CYCLE_COLLECTING_RELEASE(CanvasRenderingContext2D)
NS_IMPL_CYCLE_COLLECTION_CLASS(CanvasRenderingContext2D)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(CanvasRenderingContext2D)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCanvasElement)
for (uint32_t i = 0; i < tmp->mStyleStack.Length(); i++) {
ImplCycleCollectionUnlink(tmp->mStyleStack[i].patternStyles[Style::STROKE]);
ImplCycleCollectionUnlink(tmp->mStyleStack[i].patternStyles[Style::FILL]);
ImplCycleCollectionUnlink(tmp->mStyleStack[i].gradientStyles[Style::STROKE]);
ImplCycleCollectionUnlink(tmp->mStyleStack[i].gradientStyles[Style::FILL]);
}
for (size_t x = 0 ; x < tmp->mHitRegionsOptions.Length(); x++) {
RegionInfo& info = tmp->mHitRegionsOptions[x];
if (info.mElement) {
ImplCycleCollectionUnlink(info.mElement);
}
}
NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(CanvasRenderingContext2D)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCanvasElement)
for (uint32_t i = 0; i < tmp->mStyleStack.Length(); i++) {
ImplCycleCollectionTraverse(cb, tmp->mStyleStack[i].patternStyles[Style::STROKE], "Stroke CanvasPattern");
ImplCycleCollectionTraverse(cb, tmp->mStyleStack[i].patternStyles[Style::FILL], "Fill CanvasPattern");
ImplCycleCollectionTraverse(cb, tmp->mStyleStack[i].gradientStyles[Style::STROKE], "Stroke CanvasGradient");
ImplCycleCollectionTraverse(cb, tmp->mStyleStack[i].gradientStyles[Style::FILL], "Fill CanvasGradient");
}
for (size_t x = 0 ; x < tmp->mHitRegionsOptions.Length(); x++) {
RegionInfo& info = tmp->mHitRegionsOptions[x];
if (info.mElement) {
ImplCycleCollectionTraverse(cb, info.mElement, "Hit region fallback element");
}
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(CanvasRenderingContext2D)
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(CanvasRenderingContext2D)
if (nsCCUncollectableMarker::sGeneration && tmp->IsBlack()) {
dom::Element* canvasElement = tmp->mCanvasElement;
if (canvasElement) {
if (canvasElement->IsPurple()) {
canvasElement->RemovePurple();
}
dom::Element::MarkNodeChildren(canvasElement);
}
return true;
}
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(CanvasRenderingContext2D)
return nsCCUncollectableMarker::sGeneration && tmp->IsBlack();
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(CanvasRenderingContext2D)
return nsCCUncollectableMarker::sGeneration && tmp->IsBlack();
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(CanvasRenderingContext2D)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsICanvasRenderingContextInternal)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
/**
** CanvasRenderingContext2D impl
**/
// Initialize our static variables.
uint32_t CanvasRenderingContext2D::sNumLivingContexts = 0;
DrawTarget* CanvasRenderingContext2D::sErrorTarget = nullptr;
CanvasRenderingContext2D::CanvasRenderingContext2D()
: mForceSoftware(false)
// these are the default values from the Canvas spec
, mWidth(300), mHeight(150)
, mZero(false), mOpaque(false)
, mResetLayer(true)
, mIPC(false)
, mStream(nullptr)
, mIsEntireFrameInvalid(false)
, mPredictManyRedrawCalls(false), mPathTransformWillUpdate(false)
, mInvalidateCount(0)
{
sNumLivingContexts++;
SetIsDOMBinding();
}
CanvasRenderingContext2D::~CanvasRenderingContext2D()
{
Reset();
// Drop references from all CanvasRenderingContext2DUserData to this context
for (uint32_t i = 0; i < mUserDatas.Length(); ++i) {
mUserDatas[i]->Forget();
}
sNumLivingContexts--;
if (!sNumLivingContexts) {
NS_IF_RELEASE(sErrorTarget);
}
RemoveDemotableContext(this);
}
JSObject*
CanvasRenderingContext2D::WrapObject(JSContext *cx)
{
return CanvasRenderingContext2DBinding::Wrap(cx, this);
}
bool
CanvasRenderingContext2D::ParseColor(const nsAString& aString,
nscolor* aColor)
{
nsIDocument* document = mCanvasElement
? mCanvasElement->OwnerDoc()
: nullptr;
// Pass the CSS Loader object to the parser, to allow parser error
// reports to include the outer window ID.
nsCSSParser parser(document ? document->CSSLoader() : nullptr);
nsCSSValue value;
if (!parser.ParseColorString(aString, nullptr, 0, value)) {
return false;
}
if (value.IsNumericColorUnit()) {
// if we already have a color we can just use it directly
*aColor = value.GetColorValue();
} else {
// otherwise resolve it
nsIPresShell* presShell = GetPresShell();
nsRefPtr<nsStyleContext> parentContext;
if (mCanvasElement && mCanvasElement->IsInDoc()) {
// Inherit from the canvas element.
parentContext = nsComputedDOMStyle::GetStyleContextForElement(
mCanvasElement, nullptr, presShell);
}
unused << nsRuleNode::ComputeColor(
value, presShell ? presShell->GetPresContext() : nullptr, parentContext,
*aColor);
}
return true;
}
nsresult
CanvasRenderingContext2D::Reset()
{
if (mCanvasElement) {
mCanvasElement->InvalidateCanvas();
}
// only do this for non-docshell created contexts,
// since those are the ones that we created a surface for
if (mTarget && IsTargetValid() && !mDocShell) {
gCanvasAzureMemoryUsed -= mWidth * mHeight * 4;
}
mTarget = nullptr;
mStream = nullptr;
// reset hit regions
mHitRegionsOptions.ClearAndRetainStorage();
// Since the target changes the backing texture will change, and this will
// no longer be valid.
mIsEntireFrameInvalid = false;
mPredictManyRedrawCalls = false;
return NS_OK;
}
void
CanvasRenderingContext2D::SetStyleFromString(const nsAString& str,
Style whichStyle)
{
MOZ_ASSERT(!str.IsVoid());
nscolor color;
if (!ParseColor(str, &color)) {
return;
}
CurrentState().SetColorStyle(whichStyle, color);
}
void
CanvasRenderingContext2D::GetStyleAsUnion(OwningStringOrCanvasGradientOrCanvasPattern& aValue,
Style aWhichStyle)
{
const ContextState &state = CurrentState();
if (state.patternStyles[aWhichStyle]) {
aValue.SetAsCanvasPattern() = state.patternStyles[aWhichStyle];
} else if (state.gradientStyles[aWhichStyle]) {
aValue.SetAsCanvasGradient() = state.gradientStyles[aWhichStyle];
} else {
StyleColorToString(state.colorStyles[aWhichStyle], aValue.SetAsString());
}
}
// static
void
CanvasRenderingContext2D::StyleColorToString(const nscolor& aColor, nsAString& aStr)
{
// We can't reuse the normal CSS color stringification code,
// because the spec calls for a different algorithm for canvas.
if (NS_GET_A(aColor) == 255) {
CopyUTF8toUTF16(nsPrintfCString("#%02x%02x%02x",
NS_GET_R(aColor),
NS_GET_G(aColor),
NS_GET_B(aColor)),
aStr);
} else {
CopyUTF8toUTF16(nsPrintfCString("rgba(%d, %d, %d, ",
NS_GET_R(aColor),
NS_GET_G(aColor),
NS_GET_B(aColor)),
aStr);
aStr.AppendFloat(nsStyleUtil::ColorComponentToFloat(NS_GET_A(aColor)));
aStr.Append(')');
}
}
nsresult
CanvasRenderingContext2D::Redraw()
{
if (mIsEntireFrameInvalid) {
return NS_OK;
}
mIsEntireFrameInvalid = true;
if (!mCanvasElement) {
NS_ASSERTION(mDocShell, "Redraw with no canvas element or docshell!");
return NS_OK;
}
nsSVGEffects::InvalidateDirectRenderingObservers(mCanvasElement);
mCanvasElement->InvalidateCanvasContent(nullptr);
return NS_OK;
}
void
CanvasRenderingContext2D::Redraw(const mgfx::Rect &r)
{
++mInvalidateCount;
if (mIsEntireFrameInvalid) {
return;
}
if (mPredictManyRedrawCalls ||
mInvalidateCount > kCanvasMaxInvalidateCount) {
Redraw();
return;
}
if (!mCanvasElement) {
NS_ASSERTION(mDocShell, "Redraw with no canvas element or docshell!");
return;
}
nsSVGEffects::InvalidateDirectRenderingObservers(mCanvasElement);
mCanvasElement->InvalidateCanvasContent(&r);
}
void
CanvasRenderingContext2D::RedrawUser(const gfxRect& r)
{
if (mIsEntireFrameInvalid) {
++mInvalidateCount;
return;
}
mgfx::Rect newr =
mTarget->GetTransform().TransformBounds(ToRect(r));
Redraw(newr);
}
void CanvasRenderingContext2D::Demote()
{
if (!IsTargetValid() || mForceSoftware || !mStream)
return;
RemoveDemotableContext(this);
RefPtr<SourceSurface> snapshot = mTarget->Snapshot();
RefPtr<DrawTarget> oldTarget = mTarget;
mTarget = nullptr;
mStream = nullptr;
mResetLayer = true;
mForceSoftware = true;
// Recreate target, now demoted to software only
EnsureTarget();
if (!IsTargetValid())
return;
// Restore the content from the old DrawTarget
mgfx::Rect r(0, 0, mWidth, mHeight);
mTarget->DrawSurface(snapshot, r, r);
// Restore the clips and transform
for (uint32_t i = 0; i < CurrentState().clipsPushed.size(); i++) {
mTarget->PushClip(CurrentState().clipsPushed[i]);
}
mTarget->SetTransform(oldTarget->GetTransform());
}
std::vector<CanvasRenderingContext2D*>&
CanvasRenderingContext2D::DemotableContexts()
{
static std::vector<CanvasRenderingContext2D*> contexts;
return contexts;
}
void
CanvasRenderingContext2D::DemoteOldestContextIfNecessary()
{
const size_t kMaxContexts = 64;
std::vector<CanvasRenderingContext2D*>& contexts = DemotableContexts();
if (contexts.size() < kMaxContexts)
return;
CanvasRenderingContext2D* oldest = contexts.front();
oldest->Demote();
}
void
CanvasRenderingContext2D::AddDemotableContext(CanvasRenderingContext2D* context)
{
std::vector<CanvasRenderingContext2D*>::iterator iter = std::find(DemotableContexts().begin(), DemotableContexts().end(), context);
if (iter != DemotableContexts().end())
return;
DemotableContexts().push_back(context);
}
void
CanvasRenderingContext2D::RemoveDemotableContext(CanvasRenderingContext2D* context)
{
std::vector<CanvasRenderingContext2D*>::iterator iter = std::find(DemotableContexts().begin(), DemotableContexts().end(), context);
if (iter != DemotableContexts().end())
DemotableContexts().erase(iter);
}
bool
CanvasRenderingContext2D::CheckSizeForSkiaGL(IntSize size) {
MOZ_ASSERT(NS_IsMainThread());
int minsize = Preferences::GetInt("gfx.canvas.min-size-for-skia-gl", 128);
if (size.width < minsize || size.height < minsize) {
return false;
}
// Maximum pref allows 3 different options:
// 0 means unlimited size
// > 0 means use value as an absolute threshold
// < 0 means use the number of screen pixels as a threshold
int maxsize = Preferences::GetInt("gfx.canvas.max-size-for-skia-gl", 0);
// unlimited max size
if (!maxsize) {
return true;
}
// absolute max size threshold
if (maxsize > 0) {
return size.width <= maxsize && size.height <= maxsize;
}
// Cache the number of pixels on the primary screen
static int32_t gScreenPixels = -1;
if (gScreenPixels < 0) {
// Default to historical mobile screen size of 980x480. In addition,
// allow skia use up to this size even if the screen is smaller. A lot
// content expects this size to work well.
gScreenPixels = 980 * 480;
nsCOMPtr<nsIScreenManager> screenManager =
do_GetService("@mozilla.org/gfx/screenmanager;1");
if (screenManager) {
nsCOMPtr<nsIScreen> primaryScreen;
screenManager->GetPrimaryScreen(getter_AddRefs(primaryScreen));
if (primaryScreen) {
int32_t x, y, width, height;
primaryScreen->GetRect(&x, &y, &width, &height);
gScreenPixels = std::max(gScreenPixels, width * height);
}
}
}
// On high DPI devices the screen pixels may be scaled up. Make
// sure to apply that scaling here as well if we are hooked up
// to a widget.
static double gDefaultScale = 0.0;
if (gDefaultScale < 1.0) {
nsIPresShell* ps = GetPresShell();
if (ps) {
nsIFrame* frame = ps->GetRootFrame();
if (frame) {
nsIWidget* widget = frame->GetNearestWidget();
if (widget) {
gDefaultScale = widget->GetDefaultScale().scale;
}
}
}
}
double scale = gDefaultScale > 0 ? gDefaultScale : 1.0;
int32_t threshold = ceil(scale * scale * gScreenPixels);
// screen size acts as max threshold
return threshold < 0 || (size.width * size.height) <= threshold;
}
void
CanvasRenderingContext2D::EnsureTarget()
{
if (mTarget) {
return;
}
// Check that the dimensions are sane
IntSize size(mWidth, mHeight);
if (size.width <= 0xFFFF && size.height <= 0xFFFF &&
size.width >= 0 && size.height >= 0) {
SurfaceFormat format = GetSurfaceFormat();
nsIDocument* ownerDoc = nullptr;
if (mCanvasElement) {
ownerDoc = mCanvasElement->OwnerDoc();
}
nsRefPtr<LayerManager> layerManager = nullptr;
if (ownerDoc) {
layerManager =
nsContentUtils::PersistentLayerManagerForDocument(ownerDoc);
}
if (layerManager) {
if (gfxPlatform::GetPlatform()->UseAcceleratedSkiaCanvas() &&
!mForceSoftware &&
CheckSizeForSkiaGL(size)) {
DemoteOldestContextIfNecessary();
SkiaGLGlue* glue = gfxPlatform::GetPlatform()->GetSkiaGLGlue();
#if USE_SKIA
if (glue && glue->GetGrContext() && glue->GetGLContext()) {
mTarget = Factory::CreateDrawTargetSkiaWithGrContext(glue->GetGrContext(), size, format);
if (mTarget) {
mStream = gl::SurfaceStream::CreateForType(gl::SurfaceStreamType::TripleBuffer,
glue->GetGLContext());
AddDemotableContext(this);
} else {
printf_stderr("Failed to create a SkiaGL DrawTarget, falling back to software\n");
}
}
#endif
if (!mTarget) {
mTarget = layerManager->CreateDrawTarget(size, format);
}
} else
mTarget = layerManager->CreateDrawTarget(size, format);
} else {
mTarget = gfxPlatform::GetPlatform()->CreateOffscreenCanvasDrawTarget(size, format);
}
}
if (mTarget) {
static bool registered = false;
if (!registered) {
registered = true;
RegisterStrongMemoryReporter(new Canvas2dPixelsReporter());
}
gCanvasAzureMemoryUsed += mWidth * mHeight * 4;
JSContext* context = nsContentUtils::GetCurrentJSContext();
if (context) {
JS_updateMallocCounter(context, mWidth * mHeight * 4);
}
mTarget->ClearRect(mgfx::Rect(Point(0, 0), Size(mWidth, mHeight)));
if (mTarget->GetBackendType() == mgfx::BackendType::CAIRO) {
// Cairo doesn't play well with huge clips. When given a very big clip it
// will try to allocate big mask surface without taking the target
// size into account which can cause OOM. See bug 1034593.
// This limits the clip extents to the size of the canvas.
// A fix in Cairo would probably be preferable, but requires somewhat
// invasive changes.
mTarget->PushClipRect(mgfx::Rect(Point(0, 0), Size(mWidth, mHeight)));
}
// Force a full layer transaction since we didn't have a layer before
// and now we might need one.
if (mCanvasElement) {
mCanvasElement->InvalidateCanvas();
}
// Calling Redraw() tells our invalidation machinery that the entire
// canvas is already invalid, which can speed up future drawing.
Redraw();
} else {
EnsureErrorTarget();
mTarget = sErrorTarget;
}
}