forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsCanvasRenderingContext2DAzure.cpp
4426 lines (3627 loc) · 126 KB
/
nsCanvasRenderingContext2DAzure.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: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Corporation code.
*
* The Initial Developer of the Original Code is Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bas Schouten <bschouten@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "base/basictypes.h"
#include "nsIDOMXULElement.h"
#include "prmem.h"
#include "prenv.h"
#include "nsIServiceManager.h"
#include "nsMathUtils.h"
#include "nsContentUtils.h"
#include "nsIDOMDocument.h"
#include "nsIDocument.h"
#include "nsIDOMCanvasRenderingContext2D.h"
#include "nsICanvasRenderingContextInternal.h"
#include "nsHTMLCanvasElement.h"
#include "nsSVGEffects.h"
#include "nsPresContext.h"
#include "nsIPresShell.h"
#include "nsIVariant.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIFrame.h"
#include "nsDOMError.h"
#include "nsIScriptError.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 "nsIScriptSecurityManager.h"
#include "nsIDocShell.h"
#include "nsIDOMWindow.h"
#include "nsPIDOMWindow.h"
#include "nsIDocShell.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocShellTreeNode.h"
#include "nsIXPConnect.h"
#include "jsapi.h"
#include "nsDisplayList.h"
#include "nsTArray.h"
#include "imgIEncoder.h"
#include "gfxContext.h"
#include "gfxASurface.h"
#include "gfxImageSurface.h"
#include "gfxPlatform.h"
#include "gfxFont.h"
#include "gfxTextRunCache.h"
#include "gfxBlur.h"
#include "gfxUtils.h"
#include "nsFrameManager.h"
#include "nsFrameLoader.h"
#include "nsBidiPresUtils.h"
#include "Layers.h"
#include "CanvasUtils.h"
#include "nsIMemoryReporter.h"
#include "nsStyleUtil.h"
#include "CanvasImageCache.h"
#include <algorithm>
#include "mozilla/dom/ContentParent.h"
#include "mozilla/ipc/PDocumentRendererParent.h"
#include "mozilla/dom/PBrowserParent.h"
#include "mozilla/ipc/DocumentRendererParent.h"
#include "mozilla/gfx/2D.h"
#ifdef XP_WIN
#include "gfxWindowsPlatform.h"
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#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::dom;
using namespace mozilla::gfx;
using namespace mozilla::ipc;
using namespace mozilla::layers;
namespace mgfx = mozilla::gfx;
static float kDefaultFontSize = 10.0;
static NS_NAMED_LITERAL_STRING(kDefaultFontName, "sans-serif");
static NS_NAMED_LITERAL_STRING(kDefaultFontStyle, "10px sans-serif");
/* Memory reporter stuff */
static nsIMemoryReporter *gCanvasAzureMemoryReporter = nsnull;
static PRInt64 gCanvasAzureMemoryUsed = 0;
static PRInt64 GetCanvasAzureMemoryUsed() {
return gCanvasAzureMemoryUsed;
}
// 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.
NS_MEMORY_REPORTER_IMPLEMENT(CanvasAzureMemory,
"canvas-2d-pixel-bytes",
KIND_OTHER,
UNITS_BYTES,
GetCanvasAzureMemoryUsed,
"Memory used by 2D canvases. Each canvas requires (width * height * 4) "
"bytes.")
/**
** nsCanvasGradientAzure
**/
#define NS_CANVASGRADIENTAZURE_PRIVATE_IID \
{0x28425a6a, 0x90e0, 0x4d42, {0x9c, 0x75, 0xff, 0x60, 0x09, 0xb3, 0x10, 0xa8}}
class nsCanvasGradientAzure : public nsIDOMCanvasGradient
{
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_CANVASGRADIENTAZURE_PRIVATE_IID)
enum Type
{
LINEAR = 0,
RADIAL
};
Type GetType()
{
return mType;
}
GradientStops *GetGradientStopsForTarget(DrawTarget *aRT)
{
if (mStops && mStops->GetBackendType() == aRT->GetType()) {
return mStops;
}
mStops = aRT->CreateGradientStops(mRawStops.Elements(), mRawStops.Length());
return mStops;
}
NS_DECL_ISUPPORTS
/* nsIDOMCanvasGradient */
NS_IMETHOD AddColorStop (float offset,
const nsAString& colorstr)
{
if (!FloatValidate(offset) || offset < 0.0 || offset > 1.0) {
return NS_ERROR_DOM_INDEX_SIZE_ERR;
}
nscolor color;
nsCSSParser parser;
nsresult rv = parser.ParseColorString(nsString(colorstr),
nsnull, 0, &color);
if (NS_FAILED(rv)) {
return NS_ERROR_DOM_SYNTAX_ERR;
}
mStops = nsnull;
GradientStop newStop;
newStop.offset = offset;
newStop.color = Color::FromABGR(color);
mRawStops.AppendElement(newStop);
return NS_OK;
}
protected:
nsCanvasGradientAzure(Type aType) : mType(aType)
{}
nsTArray<GradientStop> mRawStops;
RefPtr<GradientStops> mStops;
Type mType;
};
class nsCanvasRadialGradientAzure : public nsCanvasGradientAzure
{
public:
nsCanvasRadialGradientAzure(const Point &aBeginOrigin, Float aBeginRadius,
const Point &aEndOrigin, Float aEndRadius)
: nsCanvasGradientAzure(RADIAL)
, mCenter1(aBeginOrigin)
, mCenter2(aEndOrigin)
, mRadius1(aBeginRadius)
, mRadius2(aEndRadius)
{
}
Point mCenter1;
Point mCenter2;
Float mRadius1;
Float mRadius2;
};
class nsCanvasLinearGradientAzure : public nsCanvasGradientAzure
{
public:
nsCanvasLinearGradientAzure(const Point &aBegin, const Point &aEnd)
: nsCanvasGradientAzure(LINEAR)
, mBegin(aBegin)
, mEnd(aEnd)
{
}
protected:
friend class nsCanvasRenderingContext2DAzure;
// Beginning of linear gradient.
Point mBegin;
// End of linear gradient.
Point mEnd;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsCanvasGradientAzure, NS_CANVASGRADIENTAZURE_PRIVATE_IID)
NS_IMPL_ADDREF(nsCanvasGradientAzure)
NS_IMPL_RELEASE(nsCanvasGradientAzure)
// XXX
// DOMCI_DATA(CanvasGradient, nsCanvasGradientAzure)
NS_INTERFACE_MAP_BEGIN(nsCanvasGradientAzure)
NS_INTERFACE_MAP_ENTRY(nsCanvasGradientAzure)
NS_INTERFACE_MAP_ENTRY(nsIDOMCanvasGradient)
NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(CanvasGradient)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
/**
** nsCanvasPatternAzure
**/
#define NS_CANVASPATTERNAZURE_PRIVATE_IID \
{0xc9bacc25, 0x28da, 0x421e, {0x9a, 0x4b, 0xbb, 0xd6, 0x93, 0x05, 0x12, 0xbc}}
class nsCanvasPatternAzure : public nsIDOMCanvasPattern
{
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_CANVASPATTERNAZURE_PRIVATE_IID)
enum RepeatMode
{
REPEAT,
REPEATX,
REPEATY,
NOREPEAT
};
nsCanvasPatternAzure(SourceSurface* aSurface,
RepeatMode aRepeat,
nsIPrincipal* principalForSecurityCheck,
PRBool forceWriteOnly)
: mSurface(aSurface)
, mRepeat(aRepeat)
, mPrincipal(principalForSecurityCheck)
, mForceWriteOnly(forceWriteOnly)
{
}
NS_DECL_ISUPPORTS
RefPtr<SourceSurface> mSurface;
RepeatMode mRepeat;
nsCOMPtr<nsIPrincipal> mPrincipal;
PRPackedBool mForceWriteOnly;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsCanvasPatternAzure, NS_CANVASPATTERNAZURE_PRIVATE_IID)
NS_IMPL_ADDREF(nsCanvasPatternAzure)
NS_IMPL_RELEASE(nsCanvasPatternAzure)
// XXX
// DOMCI_DATA(CanvasPattern, nsCanvasPatternAzure)
NS_INTERFACE_MAP_BEGIN(nsCanvasPatternAzure)
NS_INTERFACE_MAP_ENTRY(nsCanvasPatternAzure)
NS_INTERFACE_MAP_ENTRY(nsIDOMCanvasPattern)
NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(CanvasPattern)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
/**
** nsTextMetricsAzure
**/
#define NS_TEXTMETRICSAZURE_PRIVATE_IID \
{0x9793f9e7, 0x9dc1, 0x4e9c, {0x81, 0xc8, 0xfc, 0xa7, 0x14, 0xf4, 0x30, 0x79}}
class nsTextMetricsAzure : public nsIDOMTextMetrics
{
public:
nsTextMetricsAzure(float w) : width(w) { }
virtual ~nsTextMetricsAzure() { }
NS_DECLARE_STATIC_IID_ACCESSOR(NS_TEXTMETRICSAZURE_PRIVATE_IID)
NS_IMETHOD GetWidth(float* w) {
*w = width;
return NS_OK;
}
NS_DECL_ISUPPORTS
private:
float width;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsTextMetricsAzure, NS_TEXTMETRICSAZURE_PRIVATE_IID)
NS_IMPL_ADDREF(nsTextMetricsAzure)
NS_IMPL_RELEASE(nsTextMetricsAzure)
// XXX
// DOMCI_DATA(TextMetrics, nsTextMetricsAzure)
NS_INTERFACE_MAP_BEGIN(nsTextMetricsAzure)
NS_INTERFACE_MAP_ENTRY(nsTextMetricsAzure)
NS_INTERFACE_MAP_ENTRY(nsIDOMTextMetrics)
NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(TextMetrics)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
struct nsCanvasBidiProcessorAzure;
// Cap sigma to avoid overly large temp surfaces.
static const Float SIGMA_MAX = 100;
/**
** nsCanvasRenderingContext2DAzure
**/
class nsCanvasRenderingContext2DAzure :
public nsIDOMCanvasRenderingContext2D,
public nsICanvasRenderingContextInternal
{
public:
nsCanvasRenderingContext2DAzure();
virtual ~nsCanvasRenderingContext2DAzure();
nsresult Redraw();
// nsICanvasRenderingContextInternal
NS_IMETHOD SetCanvasElement(nsHTMLCanvasElement* aParentCanvas);
NS_IMETHOD SetDimensions(PRInt32 width, PRInt32 height);
NS_IMETHOD InitializeWithSurface(nsIDocShell *shell, gfxASurface *surface, PRInt32 width, PRInt32 height)
{ return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHOD Render(gfxContext *ctx, gfxPattern::GraphicsFilter aFilter);
NS_IMETHOD GetInputStream(const char* aMimeType,
const PRUnichar* aEncoderOptions,
nsIInputStream **aStream);
NS_IMETHOD GetThebesSurface(gfxASurface **surface);
TemporaryRef<SourceSurface> GetSurfaceSnapshot()
{ return mTarget ? mTarget->Snapshot() : nsnull; }
NS_IMETHOD SetIsOpaque(PRBool isOpaque);
NS_IMETHOD Reset();
already_AddRefed<CanvasLayer> GetCanvasLayer(nsDisplayListBuilder* aBuilder,
CanvasLayer *aOldLayer,
LayerManager *aManager);
void MarkContextClean();
NS_IMETHOD SetIsIPC(PRBool isIPC);
// this rect is in canvas device space
void Redraw(const mgfx::Rect &r);
NS_IMETHOD Redraw(const gfxRect &r) { Redraw(ToRect(r)); return NS_OK; }
// this rect is in mTarget's current user space
nsresult RedrawUser(const gfxRect &r);
// nsISupports interface + CC
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsCanvasRenderingContext2DAzure, nsIDOMCanvasRenderingContext2D)
// nsIDOMCanvasRenderingContext2D interface
NS_DECL_NSIDOMCANVASRENDERINGCONTEXT2D
enum Style {
STYLE_STROKE = 0,
STYLE_FILL,
STYLE_MAX
};
protected:
nsresult InitializeWithTarget(DrawTarget *surface, PRInt32 width, PRInt32 height);
/**
* The number of living nsCanvasRenderingContexts. When this goes down to
* 0, we free the premultiply and unpremultiply tables, if they exist.
*/
static PRUint32 sNumLivingContexts;
/**
* Lookup table used to speed up GetImageData().
*/
static PRUint8 (*sUnpremultiplyTable)[256];
/**
* Lookup table used to speed up PutImageData().
*/
static PRUint8 (*sPremultiplyTable)[256];
// Some helpers. Doesn't modify a color on failure.
nsresult SetStyleFromStringOrInterface(const nsAString& aStr, nsISupports *aInterface, Style aWhichStyle);
nsresult GetStyleAsStringOrInterface(nsAString& aStr, nsISupports **aInterface, PRInt32 *aType, Style aWhichStyle);
void StyleColorToString(const nscolor& aColor, nsAString& aStr);
/**
* Creates the unpremultiply lookup table, if it doesn't exist.
*/
void EnsureUnpremultiplyTable();
/**
* Creates the premultiply lookup table, if it doesn't exist.
*/
void EnsurePremultiplyTable();
/* This function ensures there is a writable pathbuilder available, this
* pathbuilder may be working in user space or in device space or
* device space.
*/
void EnsureWritablePath();
// Ensures a path in UserSpace is available.
void EnsureUserSpacePath();
void TransformWillUpdate();
// Report the fillRule has changed.
void FillRuleChanged();
/**
* Returns the surface format this canvas should be allocated using. Takes
* into account mOpaque, platform requirements, etc.
*/
SurfaceFormat GetSurfaceFormat() const;
nsHTMLCanvasElement *HTMLCanvasElement() {
return static_cast<nsHTMLCanvasElement*>(mCanvasElement.get());
}
// Member vars
PRInt32 mWidth, mHeight;
// This is true when the canvas is valid, false otherwise, this occurs when
// for some reason initialization of the drawtarget fails. If the canvas
// is invalid certain behavior is expected.
PRPackedBool mValid;
// This is true when the canvas is valid, but of zero size, this requires
// specific behavior on some operations.
PRPackedBool mZero;
PRPackedBool mOpaque;
// This is true when the next time our layer is retrieved we need to
// recreate it (i.e. our backing surface changed)
PRPackedBool mResetLayer;
// This is needed for drawing in drawAsyncXULElement
PRPackedBool mIPC;
// the canvas element we're a context of
nsCOMPtr<nsIDOMHTMLCanvasElement> mCanvasElement;
// If mCanvasElement is not provided, then a docshell is
nsCOMPtr<nsIDocShell> mDocShell;
// our drawing surfaces, contexts, and layers
RefPtr<DrawTarget> mTarget;
/**
* Flag to avoid duplicate calls to InvalidateFrame. Set to true whenever
* Redraw is called, reset to false when Render is called.
*/
PRPackedBool mIsEntireFrameInvalid;
/**
* When this is set, the first call to Redraw(gfxRect) should set
* mIsEntireFrameInvalid since we expect it will be followed by
* many more Redraw calls.
*/
PRPackedBool mPredictManyRedrawCalls;
// This is stored after GetThebesSurface has been called once to avoid
// excessive ThebesSurface initialization overhead.
nsRefPtr<gfxASurface> mThebesSurface;
/**
* We also have a device space pathbuilder. The reason for this is as
* follows, when a path is being built, but the transform changes, we
* can no longer keep a single path in userspace, considering there's
* several 'user spaces' now. We therefore transform the current path
* into device space, and add all operations to this path in device
* space.
*
* When then finally executing a render, the Azure drawing API expects
* the path to be in userspace. We could then set an identity transform
* on the DrawTarget and do all drawing in device space. This is
* undesirable because it requires transforming patterns, gradients,
* clips, etc. into device space and it would not work for stroking.
* What we do instead is convert the path back to user space when it is
* drawn, and draw it with the current transform. This makes all drawing
* occur correctly.
*
* There's never both a device space path builder and a user space path
* builder present at the same time. There is also never a path and a
* path builder present at the same time. When writing proceeds on an
* existing path the Path is cleared and a new builder is created.
*
* mPath is always in user-space.
*/
RefPtr<Path> mPath;
RefPtr<PathBuilder> mDSPathBuilder;
RefPtr<PathBuilder> mPathBuilder;
bool mPathTransformWillUpdate;
Matrix mPathToDS;
/**
* Number of times we've invalidated before calling redraw
*/
PRUint32 mInvalidateCount;
static const PRUint32 kCanvasMaxInvalidateCount = 100;
/**
* Returns true if a shadow should be drawn along with a
* drawing operation.
*/
PRBool NeedToDrawShadow()
{
const ContextState& state = CurrentState();
// The spec says we should not draw shadows if the operator is OVER.
// If it's over and the alpha value is zero, nothing needs to be drawn.
return NS_GET_A(state.shadowColor) != 0 &&
(state.shadowBlur != 0 || state.shadowOffset.x != 0 || state.shadowOffset.y != 0);
}
CompositionOp UsedOperation()
{
if (NeedToDrawShadow()) {
// In this case the shadow rendering will use the operator.
return OP_OVER;
}
return CurrentState().op;
}
/**
* Gets the pres shell from either the canvas element or the doc shell
*/
nsIPresShell *GetPresShell() {
nsCOMPtr<nsIContent> content =
do_QueryInterface(static_cast<nsIDOMHTMLCanvasElement*>(mCanvasElement));
if (content) {
nsIDocument* ownerDoc = content->GetOwnerDoc();
return ownerDoc ? ownerDoc->GetShell() : nsnull;
}
if (mDocShell) {
nsCOMPtr<nsIPresShell> shell;
mDocShell->GetPresShell(getter_AddRefs(shell));
return shell.get();
}
return nsnull;
}
// text
enum TextAlign {
TEXT_ALIGN_START,
TEXT_ALIGN_END,
TEXT_ALIGN_LEFT,
TEXT_ALIGN_RIGHT,
TEXT_ALIGN_CENTER
};
enum TextBaseline {
TEXT_BASELINE_TOP,
TEXT_BASELINE_HANGING,
TEXT_BASELINE_MIDDLE,
TEXT_BASELINE_ALPHABETIC,
TEXT_BASELINE_IDEOGRAPHIC,
TEXT_BASELINE_BOTTOM
};
gfxFontGroup *GetCurrentFontStyle();
enum TextDrawOperation {
TEXT_DRAW_OPERATION_FILL,
TEXT_DRAW_OPERATION_STROKE,
TEXT_DRAW_OPERATION_MEASURE
};
/*
* Implementation of the fillText, strokeText, and measure functions with
* the operation abstracted to a flag.
*/
nsresult DrawOrMeasureText(const nsAString& text,
float x,
float y,
float maxWidth,
TextDrawOperation op,
float* aWidth);
// state stack handling
class ContextState {
public:
ContextState() : textAlign(TEXT_ALIGN_START),
textBaseline(TEXT_BASELINE_ALPHABETIC),
lineWidth(1.0f),
miterLimit(10.0f),
globalAlpha(1.0f),
shadowBlur(0.0),
dashOffset(0.0f),
op(OP_OVER),
fillRule(FILL_WINDING),
lineCap(CAP_BUTT),
lineJoin(JOIN_MITER_OR_BEVEL),
imageSmoothingEnabled(PR_TRUE)
{ }
ContextState(const ContextState& other)
: fontGroup(other.fontGroup),
font(other.font),
textAlign(other.textAlign),
textBaseline(other.textBaseline),
shadowColor(other.shadowColor),
transform(other.transform),
shadowOffset(other.shadowOffset),
lineWidth(other.lineWidth),
miterLimit(other.miterLimit),
globalAlpha(other.globalAlpha),
shadowBlur(other.shadowBlur),
dash(other.dash),
dashOffset(other.dashOffset),
op(other.op),
fillRule(FILL_WINDING),
lineCap(other.lineCap),
lineJoin(other.lineJoin),
imageSmoothingEnabled(other.imageSmoothingEnabled)
{
for (int i = 0; i < STYLE_MAX; i++) {
colorStyles[i] = other.colorStyles[i];
gradientStyles[i] = other.gradientStyles[i];
patternStyles[i] = other.patternStyles[i];
}
}
void SetColorStyle(Style whichStyle, nscolor color) {
colorStyles[whichStyle] = color;
gradientStyles[whichStyle] = nsnull;
patternStyles[whichStyle] = nsnull;
}
void SetPatternStyle(Style whichStyle, nsCanvasPatternAzure* pat) {
gradientStyles[whichStyle] = nsnull;
patternStyles[whichStyle] = pat;
}
void SetGradientStyle(Style whichStyle, nsCanvasGradientAzure* grad) {
gradientStyles[whichStyle] = grad;
patternStyles[whichStyle] = nsnull;
}
/**
* returns true iff the given style is a solid color.
*/
PRBool StyleIsColor(Style whichStyle) const
{
return !(patternStyles[whichStyle] ||
gradientStyles[whichStyle]);
}
std::vector<RefPtr<Path> > clipsPushed;
nsRefPtr<gfxFontGroup> fontGroup;
nsRefPtr<nsCanvasGradientAzure> gradientStyles[STYLE_MAX];
nsRefPtr<nsCanvasPatternAzure> patternStyles[STYLE_MAX];
nsString font;
TextAlign textAlign;
TextBaseline textBaseline;
nscolor colorStyles[STYLE_MAX];
nscolor shadowColor;
Matrix transform;
Point shadowOffset;
Float lineWidth;
Float miterLimit;
Float globalAlpha;
Float shadowBlur;
FallibleTArray<Float> dash;
Float dashOffset;
CompositionOp op;
FillRule fillRule;
CapStyle lineCap;
JoinStyle lineJoin;
PRPackedBool imageSmoothingEnabled;
};
class GeneralPattern
{
public:
GeneralPattern() : mPattern(nsnull) {}
~GeneralPattern()
{
if (mPattern) {
mPattern->~Pattern();
}
}
Pattern& ForStyle(nsCanvasRenderingContext2DAzure *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 GeneralPattern!");
const nsCanvasRenderingContext2DAzure::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() == nsCanvasGradientAzure::LINEAR) {
nsCanvasLinearGradientAzure *gradient =
static_cast<nsCanvasLinearGradientAzure*>(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() == nsCanvasGradientAzure::RADIAL) {
nsCanvasRadialGradientAzure *gradient =
static_cast<nsCanvasRadialGradientAzure*>(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->HTMLCanvasElement(),
state.patternStyles[aStyle]->mPrincipal,
state.patternStyles[aStyle]->mForceWriteOnly);
}
ExtendMode mode;
if (state.patternStyles[aStyle]->mRepeat == nsCanvasPatternAzure::NOREPEAT) {
mode = EXTEND_CLAMP;
} else {
mode = EXTEND_WRAP;
}
mPattern = new (mSurfacePattern.addr())
SurfacePattern(state.patternStyles[aStyle]->mSurface, mode);
}
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 NULL the drawing
* operation will be assumed to cover an infinite rect.
*/
class AdjustedTarget
{
public:
AdjustedTarget(nsCanvasRenderingContext2DAzure *ctx,
mgfx::Rect *aBounds = nsnull)
: mCtx(nsnull)
{
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);
Float blurRadius = mSigma * 3;
// We need to enlarge and possibly offset our temporary surface
// so that things outside of the canvas may cast shadows.
mTempRect.Inflate(Margin(blurRadius + NS_MAX<Float>(state.shadowOffset.x, 0),
blurRadius + NS_MAX<Float>(state.shadowOffset.y, 0),
blurRadius + NS_MAX<Float>(-state.shadowOffset.x, 0),
blurRadius + NS_MAX<Float>(-state.shadowOffset.y, 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->CreateSimilarDrawTarget(IntSize(int32_t(mTempRect.width), int32_t(mTempRect.height)),
FORMAT_B8G8R8A8);
if (!mTarget) {
// XXX - Deal with the situation where our temp size is too big to
// fit in a texture.
mTarget = ctx->mTarget;
mCtx = nsnull;
} 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);
}
DrawTarget* operator->()
{
return mTarget;
}
private:
RefPtr<DrawTarget> mTarget;
nsCanvasRenderingContext2DAzure *mCtx;
Float mSigma;
mgfx::Rect mTempRect;
};
nsAutoTArray<ContextState, 3> mStyleStack;
inline ContextState& CurrentState() {
return mStyleStack[mStyleStack.Length() - 1];
}
// other helpers
void GetAppUnitsValues(PRUint32 *perDevPixel, PRUint32 *perCSSPixel) {
// If we don't have a canvas element, we just return something generic.
PRUint32 devPixel = 60;
PRUint32 cssPixel = 60;
nsIPresShell *ps = GetPresShell();
nsPresContext *pc;
if (!ps) goto FINISH;
pc = ps->GetPresContext();
if (!pc) goto FINISH;
devPixel = pc->AppUnitsPerDevPixel();
cssPixel = pc->AppUnitsPerCSSPixel();
FINISH:
if (perDevPixel)
*perDevPixel = devPixel;
if (perCSSPixel)
*perCSSPixel = cssPixel;
}
friend struct nsCanvasBidiProcessorAzure;
};
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsCanvasRenderingContext2DAzure)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsCanvasRenderingContext2DAzure)
NS_IMPL_CYCLE_COLLECTION_CLASS(nsCanvasRenderingContext2DAzure)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsCanvasRenderingContext2DAzure)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCanvasElement)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsCanvasRenderingContext2DAzure)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCanvasElement)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
// XXX
// DOMCI_DATA(CanvasRenderingContext2D, nsCanvasRenderingContext2DAzure)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsCanvasRenderingContext2DAzure)
NS_INTERFACE_MAP_ENTRY(nsIDOMCanvasRenderingContext2D)
NS_INTERFACE_MAP_ENTRY(nsICanvasRenderingContextInternal)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMCanvasRenderingContext2D)
NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(CanvasRenderingContext2D)
NS_INTERFACE_MAP_END
/**
** CanvasRenderingContext2D impl
**/
// Initialize our static variables.
PRUint32 nsCanvasRenderingContext2DAzure::sNumLivingContexts = 0;
PRUint8 (*nsCanvasRenderingContext2DAzure::sUnpremultiplyTable)[256] = nsnull;
PRUint8 (*nsCanvasRenderingContext2DAzure::sPremultiplyTable)[256] = nsnull;
nsresult
NS_NewCanvasRenderingContext2DAzure(nsIDOMCanvasRenderingContext2D** aResult)
{
#ifndef XP_WIN
return NS_ERROR_NOT_AVAILABLE;
#else
if (gfxWindowsPlatform::GetPlatform()->GetRenderMode() !=
gfxWindowsPlatform::RENDER_DIRECT2D ||
!gfxWindowsPlatform::GetPlatform()->DWriteEnabled()) {
return NS_ERROR_NOT_AVAILABLE;
}
nsRefPtr<nsIDOMCanvasRenderingContext2D> ctx = new nsCanvasRenderingContext2DAzure();
if (!ctx)
return NS_ERROR_OUT_OF_MEMORY;