forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsImageFrame.cpp
2063 lines (1766 loc) · 66.3 KB
/
nsImageFrame.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/. */
/* rendering object for replaced elements with bitmap image data */
#include "mozilla/DebugOnly.h"
#include "nsHTMLParts.h"
#include "nsCOMPtr.h"
#include "nsImageFrame.h"
#include "nsIImageLoadingContent.h"
#include "nsString.h"
#include "nsPrintfCString.h"
#include "nsPresContext.h"
#include "nsRenderingContext.h"
#include "nsIPresShell.h"
#include "nsGkAtoms.h"
#include "nsIDocument.h"
#include "nsINodeInfo.h"
#include "nsContentUtils.h"
#include "nsCSSAnonBoxes.h"
#include "nsStyleContext.h"
#include "nsStyleConsts.h"
#include "nsStyleCoord.h"
#include "nsTransform2D.h"
#include "nsImageMap.h"
#include "nsILinkHandler.h"
#include "nsIURL.h"
#include "nsIIOService.h"
#include "nsILoadGroup.h"
#include "nsISupportsPriority.h"
#include "nsIServiceManager.h"
#include "nsNetUtil.h"
#include "nsContainerFrame.h"
#include "prprf.h"
#include "nsCSSRendering.h"
#include "nsILink.h"
#include "nsIDOMHTMLAnchorElement.h"
#include "nsIDOMHTMLImageElement.h"
#include "nsINameSpaceManager.h"
#include "nsTextFragment.h"
#include "nsIDOMHTMLMapElement.h"
#include "nsIScriptSecurityManager.h"
#ifdef ACCESSIBILITY
#include "nsAccessibilityService.h"
#endif
#include "nsIDOMNode.h"
#include "nsGUIEvent.h"
#include "nsLayoutUtils.h"
#include "nsDisplayList.h"
#include "imgIContainer.h"
#include "imgLoader.h"
#include "imgRequestProxy.h"
#include "nsCSSFrameConstructor.h"
#include "nsIDOMRange.h"
#include "nsIContentPolicy.h"
#include "nsContentPolicyUtils.h"
#include "nsEventStates.h"
#include "nsError.h"
#include "nsBidiUtils.h"
#include "nsBidiPresUtils.h"
#include "gfxRect.h"
#include "ImageLayers.h"
#include "ImageContainer.h"
#include "mozilla/Preferences.h"
using namespace mozilla;
// sizes (pixels) for image icon, padding and border frame
#define ICON_SIZE (16)
#define ICON_PADDING (3)
#define ALT_BORDER_WIDTH (1)
//we must add hooks soon
#define IMAGE_EDITOR_CHECK 1
// Default alignment value (so we can tell an unset value from a set value)
#define ALIGN_UNSET uint8_t(-1)
using namespace mozilla::layers;
using namespace mozilla::dom;
// static icon information
nsImageFrame::IconLoad* nsImageFrame::gIconLoad = nullptr;
// cached IO service for loading icons
nsIIOService* nsImageFrame::sIOService;
// test if the width and height are fixed, looking at the style data
static bool HaveFixedSize(const nsStylePosition* aStylePosition)
{
// check the width and height values in the reflow state's style struct
// - if width and height are specified as either coord or percentage, then
// the size of the image frame is constrained
return aStylePosition->mWidth.IsCoordPercentCalcUnit() &&
aStylePosition->mHeight.IsCoordPercentCalcUnit();
}
// use the data in the reflow state to decide if the image has a constrained size
// (i.e. width and height that are based on the containing block size and not the image size)
// so we can avoid animated GIF related reflows
inline bool HaveFixedSize(const nsHTMLReflowState& aReflowState)
{
NS_ASSERTION(aReflowState.mStylePosition, "crappy reflowState - null stylePosition");
// when an image has percent css style height or width, but ComputedHeight()
// or ComputedWidth() of reflow state is NS_UNCONSTRAINEDSIZE
// it needs to return false to cause an incremental reflow later
// if an image is inside table like bug 156731 simple testcase III,
// during pass 1 reflow, ComputedWidth() is NS_UNCONSTRAINEDSIZE
// in pass 2 reflow, ComputedWidth() is 0, it also needs to return false
// see bug 156731
const nsStyleCoord &height = aReflowState.mStylePosition->mHeight;
const nsStyleCoord &width = aReflowState.mStylePosition->mWidth;
return ((height.HasPercent() &&
NS_UNCONSTRAINEDSIZE == aReflowState.ComputedHeight()) ||
(width.HasPercent() &&
(NS_UNCONSTRAINEDSIZE == aReflowState.ComputedWidth() ||
0 == aReflowState.ComputedWidth())))
? false
: HaveFixedSize(aReflowState.mStylePosition);
}
nsIFrame*
NS_NewImageFrame(nsIPresShell* aPresShell, nsStyleContext* aContext)
{
return new (aPresShell) nsImageFrame(aContext);
}
NS_IMPL_FRAMEARENA_HELPERS(nsImageFrame)
nsImageFrame::nsImageFrame(nsStyleContext* aContext) :
ImageFrameSuper(aContext),
mComputedSize(0, 0),
mIntrinsicRatio(0, 0),
mDisplayingIcon(false),
mFirstFrameComplete(false)
{
// We assume our size is not constrained and we haven't gotten an
// initial reflow yet, so don't touch those flags.
mIntrinsicSize.width.SetCoordValue(0);
mIntrinsicSize.height.SetCoordValue(0);
}
nsImageFrame::~nsImageFrame()
{
}
NS_QUERYFRAME_HEAD(nsImageFrame)
NS_QUERYFRAME_ENTRY(nsImageFrame)
NS_QUERYFRAME_TAIL_INHERITING(ImageFrameSuper)
#ifdef ACCESSIBILITY
a11y::AccType
nsImageFrame::AccessibleType()
{
// Don't use GetImageMap() to avoid reentrancy into accessibility.
if (HasImageMap()) {
return a11y::eHTMLImageMapType;
}
return a11y::eImageType;
}
#endif
void
nsImageFrame::DisconnectMap()
{
if (mImageMap) {
mImageMap->Destroy();
NS_RELEASE(mImageMap);
#ifdef ACCESSIBILITY
nsAccessibilityService* accService = GetAccService();
if (accService) {
accService->RecreateAccessible(PresContext()->PresShell(), mContent);
}
#endif
}
}
void
nsImageFrame::DestroyFrom(nsIFrame* aDestructRoot)
{
// Tell our image map, if there is one, to clean up
// This causes the nsImageMap to unregister itself as
// a DOM listener.
DisconnectMap();
// set the frame to null so we don't send messages to a dead object.
if (mListener) {
nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
if (imageLoader) {
// Push a null JSContext on the stack so that code that runs
// within the below code doesn't think it's being called by
// JS. See bug 604262.
nsCxPusher pusher;
pusher.PushNull();
// Notify our image loading content that we are going away so it can
// deregister with our refresh driver.
imageLoader->FrameDestroyed(this);
imageLoader->RemoveObserver(mListener);
}
reinterpret_cast<nsImageListener*>(mListener.get())->SetFrame(nullptr);
}
mListener = nullptr;
// If we were displaying an icon, take ourselves off the list
if (mDisplayingIcon)
gIconLoad->RemoveIconObserver(this);
nsSplittableFrame::DestroyFrom(aDestructRoot);
}
NS_IMETHODIMP
nsImageFrame::Init(nsIContent* aContent,
nsIFrame* aParent,
nsIFrame* aPrevInFlow)
{
nsresult rv = nsSplittableFrame::Init(aContent, aParent, aPrevInFlow);
NS_ENSURE_SUCCESS(rv, rv);
mListener = new nsImageListener(this);
nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(aContent);
NS_ENSURE_TRUE(imageLoader, NS_ERROR_UNEXPECTED);
{
// Push a null JSContext on the stack so that code that runs
// within the below code doesn't think it's being called by
// JS. See bug 604262.
nsCxPusher pusher;
pusher.PushNull();
imageLoader->AddObserver(mListener);
}
nsPresContext *aPresContext = PresContext();
if (!gIconLoad)
LoadIcons(aPresContext);
// We have a PresContext now, so we need to notify the image content node
// that it can register images.
imageLoader->FrameCreated(this);
// Give image loads associated with an image frame a small priority boost!
nsCOMPtr<imgIRequest> currentRequest;
imageLoader->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
getter_AddRefs(currentRequest));
nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(currentRequest);
if (p)
p->AdjustPriority(-1);
// If we already have an image container, OnStartContainer won't be called
// Set the animation mode here
if (currentRequest) {
nsCOMPtr<imgIContainer> image;
currentRequest->GetImage(getter_AddRefs(image));
if (image) {
image->SetAnimationMode(aPresContext->ImageAnimationMode());
}
}
return rv;
}
bool
nsImageFrame::UpdateIntrinsicSize(imgIContainer* aImage)
{
NS_PRECONDITION(aImage, "null image");
if (!aImage)
return false;
nsIFrame::IntrinsicSize oldIntrinsicSize = mIntrinsicSize;
nsIFrame* rootFrame = aImage->GetRootLayoutFrame();
if (rootFrame) {
// Set intrinsic size to match that of aImage's rootFrame.
mIntrinsicSize = rootFrame->GetIntrinsicSize();
} else {
// Set intrinsic size to match aImage's reported width & height.
nsIntSize imageSizeInPx;
if (NS_FAILED(aImage->GetWidth(&imageSizeInPx.width)) ||
NS_FAILED(aImage->GetHeight(&imageSizeInPx.height))) {
imageSizeInPx.SizeTo(0, 0);
}
mIntrinsicSize.width.SetCoordValue(
nsPresContext::CSSPixelsToAppUnits(imageSizeInPx.width));
mIntrinsicSize.height.SetCoordValue(
nsPresContext::CSSPixelsToAppUnits(imageSizeInPx.height));
}
return mIntrinsicSize != oldIntrinsicSize;
}
bool
nsImageFrame::UpdateIntrinsicRatio(imgIContainer* aImage)
{
NS_PRECONDITION(aImage, "null image");
if (!aImage)
return false;
nsSize oldIntrinsicRatio = mIntrinsicRatio;
nsIFrame* rootFrame = aImage->GetRootLayoutFrame();
if (rootFrame) {
// Set intrinsic ratio to match that of aImage's rootFrame.
mIntrinsicRatio = rootFrame->GetIntrinsicRatio();
} else {
NS_ABORT_IF_FALSE(mIntrinsicSize.width.GetUnit() == eStyleUnit_Coord &&
mIntrinsicSize.height.GetUnit() == eStyleUnit_Coord,
"since aImage doesn't have a rootFrame, our intrinsic "
"dimensions must have coord units (not percent units)");
mIntrinsicRatio.width = mIntrinsicSize.width.GetCoordValue();
mIntrinsicRatio.height = mIntrinsicSize.height.GetCoordValue();
}
return mIntrinsicRatio != oldIntrinsicRatio;
}
bool
nsImageFrame::GetSourceToDestTransform(nsTransform2D& aTransform)
{
// Set the translation components.
// XXXbz does this introduce rounding errors because of the cast to
// float? Should we just manually add that stuff in every time
// instead?
nsRect innerArea = GetInnerArea();
aTransform.SetToTranslate(float(innerArea.x),
float(innerArea.y - GetContinuationOffset()));
// Set the scale factors.
if (mIntrinsicSize.width.GetUnit() == eStyleUnit_Coord &&
mIntrinsicSize.width.GetCoordValue() != 0 &&
mIntrinsicSize.height.GetUnit() == eStyleUnit_Coord &&
mIntrinsicSize.height.GetCoordValue() != 0 &&
mIntrinsicSize.width.GetCoordValue() != mComputedSize.width &&
mIntrinsicSize.height.GetCoordValue() != mComputedSize.height) {
aTransform.SetScale(float(mComputedSize.width) /
float(mIntrinsicSize.width.GetCoordValue()),
float(mComputedSize.height) /
float(mIntrinsicSize.height.GetCoordValue()));
return true;
}
return false;
}
/*
* These two functions basically do the same check. The first one
* checks that the given request is the current request for our
* mContent. The second checks that the given image container the
* same as the image container on the current request for our
* mContent.
*/
bool
nsImageFrame::IsPendingLoad(imgIRequest* aRequest) const
{
// Default to pending load in case of errors
nsCOMPtr<nsIImageLoadingContent> imageLoader(do_QueryInterface(mContent));
NS_ASSERTION(imageLoader, "No image loading content?");
int32_t requestType = nsIImageLoadingContent::UNKNOWN_REQUEST;
imageLoader->GetRequestType(aRequest, &requestType);
return requestType != nsIImageLoadingContent::CURRENT_REQUEST;
}
bool
nsImageFrame::IsPendingLoad(imgIContainer* aContainer) const
{
// default to pending load in case of errors
if (!aContainer) {
NS_ERROR("No image container!");
return true;
}
nsCOMPtr<nsIImageLoadingContent> imageLoader(do_QueryInterface(mContent));
NS_ASSERTION(imageLoader, "No image loading content?");
nsCOMPtr<imgIRequest> currentRequest;
imageLoader->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
getter_AddRefs(currentRequest));
if (!currentRequest) {
NS_ERROR("No current request");
return true;
}
nsCOMPtr<imgIContainer> currentContainer;
currentRequest->GetImage(getter_AddRefs(currentContainer));
return currentContainer != aContainer;
}
nsRect
nsImageFrame::SourceRectToDest(const nsIntRect& aRect)
{
// When scaling the image, row N of the source image may (depending on
// the scaling function) be used to draw any row in the destination image
// between floor(F * (N-1)) and ceil(F * (N+1)), where F is the
// floating-point scaling factor. The same holds true for columns.
// So, we start by computing that bound without the floor and ceiling.
nsRect r(nsPresContext::CSSPixelsToAppUnits(aRect.x - 1),
nsPresContext::CSSPixelsToAppUnits(aRect.y - 1),
nsPresContext::CSSPixelsToAppUnits(aRect.width + 2),
nsPresContext::CSSPixelsToAppUnits(aRect.height + 2));
nsTransform2D sourceToDest;
if (!GetSourceToDestTransform(sourceToDest)) {
// Failed to generate transform matrix. Return our whole inner area,
// to be on the safe side (since this method is used for generating
// invalidation rects).
return GetInnerArea();
}
sourceToDest.TransformCoord(&r.x, &r.y, &r.width, &r.height);
// Now, round the edges out to the pixel boundary.
nscoord scale = nsPresContext::CSSPixelsToAppUnits(1);
nscoord right = r.x + r.width;
nscoord bottom = r.y + r.height;
r.x -= (scale + (r.x % scale)) % scale;
r.y -= (scale + (r.y % scale)) % scale;
r.width = right + ((scale - (right % scale)) % scale) - r.x;
r.height = bottom + ((scale - (bottom % scale)) % scale) - r.y;
return r;
}
// Note that we treat NS_EVENT_STATE_SUPPRESSED images as "OK". This means
// that we'll construct image frames for them as needed if their display is
// toggled from "none" (though we won't paint them, unless their visibility
// is changed too).
#define BAD_STATES (NS_EVENT_STATE_BROKEN | NS_EVENT_STATE_USERDISABLED | \
NS_EVENT_STATE_LOADING)
// This is a macro so that we don't evaluate the boolean last arg
// unless we have to; it can be expensive
#define IMAGE_OK(_state, _loadingOK) \
(!(_state).HasAtLeastOneOfStates(BAD_STATES) || \
(!(_state).HasAtLeastOneOfStates(NS_EVENT_STATE_BROKEN | NS_EVENT_STATE_USERDISABLED) && \
(_state).HasState(NS_EVENT_STATE_LOADING) && (_loadingOK)))
/* static */
bool
nsImageFrame::ShouldCreateImageFrameFor(Element* aElement,
nsStyleContext* aStyleContext)
{
nsEventStates state = aElement->State();
if (IMAGE_OK(state,
HaveFixedSize(aStyleContext->GetStylePosition()))) {
// Image is fine; do the image frame thing
return true;
}
// Check if we want to use a placeholder box with an icon or just
// let the presShell make us into inline text. Decide as follows:
//
// - if our special "force icons" style is set, show an icon
// - else if our "do not show placeholders" pref is set, skip the icon
// - else:
// - if QuirksMode, and there is no alt attribute, and this is not an
// <object> (which could not possibly have such an attribute), show an
// icon.
// - if QuirksMode, and the IMG has a size show an icon.
// - otherwise, skip the icon
bool useSizedBox;
if (aStyleContext->GetStyleUIReset()->mForceBrokenImageIcon) {
useSizedBox = true;
}
else if (gIconLoad && gIconLoad->mPrefForceInlineAltText) {
useSizedBox = false;
}
else {
if (aStyleContext->PresContext()->CompatibilityMode() !=
eCompatibility_NavQuirks) {
useSizedBox = false;
}
else {
// We are in quirks mode, so we can just check the tag name; no need to
// check the namespace.
nsIAtom *localName = aElement->Tag();
// Use a sized box if we have no alt text. This means no alt attribute
// and the node is not an object or an input (since those always have alt
// text).
if (!aElement->HasAttr(kNameSpaceID_None, nsGkAtoms::alt) &&
localName != nsGkAtoms::object &&
localName != nsGkAtoms::input) {
useSizedBox = true;
}
else {
// check whether we have fixed size
useSizedBox = HaveFixedSize(aStyleContext->GetStylePosition());
}
}
}
return useSizedBox;
}
nsresult
nsImageFrame::Notify(imgIRequest* aRequest, int32_t aType, const nsIntRect* aData)
{
if (aType == imgINotificationObserver::SIZE_AVAILABLE) {
nsCOMPtr<imgIContainer> image;
aRequest->GetImage(getter_AddRefs(image));
return OnStartContainer(aRequest, image);
}
if (aType == imgINotificationObserver::FRAME_UPDATE) {
return OnDataAvailable(aRequest, aData);
}
if (aType == imgINotificationObserver::FRAME_COMPLETE) {
mFirstFrameComplete = true;
}
if (aType == imgINotificationObserver::LOAD_COMPLETE) {
uint32_t imgStatus;
aRequest->GetImageStatus(&imgStatus);
nsresult status =
imgStatus & imgIRequest::STATUS_ERROR ? NS_ERROR_FAILURE : NS_OK;
return OnStopRequest(aRequest, status);
}
return NS_OK;
}
nsresult
nsImageFrame::OnStartContainer(imgIRequest *aRequest, imgIContainer *aImage)
{
if (!aImage) return NS_ERROR_INVALID_ARG;
/* Get requested animation policy from the pres context:
* normal = 0
* one frame = 1
* one loop = 2
*/
nsPresContext *presContext = PresContext();
aImage->SetAnimationMode(presContext->ImageAnimationMode());
if (IsPendingLoad(aRequest)) {
// We don't care
return NS_OK;
}
bool intrinsicSizeChanged = UpdateIntrinsicSize(aImage);
intrinsicSizeChanged = UpdateIntrinsicRatio(aImage) || intrinsicSizeChanged;
if (intrinsicSizeChanged && (mState & IMAGE_GOTINITIALREFLOW)) {
// Now we need to reflow if we have an unconstrained size and have
// already gotten the initial reflow
if (!(mState & IMAGE_SIZECONSTRAINED)) {
nsIPresShell *presShell = presContext->GetPresShell();
NS_ASSERTION(presShell, "No PresShell.");
if (presShell) {
presShell->FrameNeedsReflow(this, nsIPresShell::eStyleChange,
NS_FRAME_IS_DIRTY);
}
}
}
return NS_OK;
}
nsresult
nsImageFrame::OnDataAvailable(imgIRequest *aRequest,
const nsIntRect *aRect)
{
if (mFirstFrameComplete) {
nsCOMPtr<imgIContainer> container;
aRequest->GetImage(getter_AddRefs(container));
return FrameChanged(aRequest, container);
}
// XXX do we need to make sure that the reflow from the
// OnStartContainer has been processed before we start calling
// invalidate?
NS_ENSURE_ARG_POINTER(aRect);
if (!(mState & IMAGE_GOTINITIALREFLOW)) {
// Don't bother to do anything; we have a reflow coming up!
return NS_OK;
}
if (IsPendingLoad(aRequest)) {
// We don't care
return NS_OK;
}
#ifdef DEBUG_decode
printf("Source rect (%d,%d,%d,%d)\n",
aRect->x, aRect->y, aRect->width, aRect->height);
#endif
if (aRect->IsEqualInterior(nsIntRect::GetMaxSizedIntRect())) {
InvalidateFrame(nsDisplayItem::TYPE_IMAGE);
InvalidateFrame(nsDisplayItem::TYPE_ALT_FEEDBACK);
} else {
nsRect invalid = SourceRectToDest(*aRect);
InvalidateFrameWithRect(invalid, nsDisplayItem::TYPE_IMAGE);
InvalidateFrameWithRect(invalid, nsDisplayItem::TYPE_ALT_FEEDBACK);
}
return NS_OK;
}
nsresult
nsImageFrame::OnStopRequest(imgIRequest *aRequest,
nsresult aStatus)
{
// Check what request type we're dealing with
nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
NS_ASSERTION(imageLoader, "Who's notifying us??");
int32_t loadType = nsIImageLoadingContent::UNKNOWN_REQUEST;
imageLoader->GetRequestType(aRequest, &loadType);
if (loadType != nsIImageLoadingContent::CURRENT_REQUEST &&
loadType != nsIImageLoadingContent::PENDING_REQUEST) {
return NS_ERROR_FAILURE;
}
bool multipart = false;
aRequest->GetMultipart(&multipart);
if (loadType == nsIImageLoadingContent::PENDING_REQUEST || multipart) {
NotifyNewCurrentRequest(aRequest, aStatus);
}
return NS_OK;
}
void
nsImageFrame::NotifyNewCurrentRequest(imgIRequest *aRequest,
nsresult aStatus)
{
// May have to switch sizes here!
bool intrinsicSizeChanged = true;
if (NS_SUCCEEDED(aStatus)) {
nsCOMPtr<imgIContainer> imageContainer;
aRequest->GetImage(getter_AddRefs(imageContainer));
NS_ASSERTION(imageContainer, "Successful load with no container?");
intrinsicSizeChanged = UpdateIntrinsicSize(imageContainer);
intrinsicSizeChanged = UpdateIntrinsicRatio(imageContainer) ||
intrinsicSizeChanged;
}
else {
// Have to size to 0,0 so that GetDesiredSize recalculates the size
mIntrinsicSize.width.SetCoordValue(0);
mIntrinsicSize.height.SetCoordValue(0);
mIntrinsicRatio.SizeTo(0, 0);
}
if (mState & IMAGE_GOTINITIALREFLOW) { // do nothing if we haven't gotten the initial reflow yet
if (!(mState & IMAGE_SIZECONSTRAINED) && intrinsicSizeChanged) {
nsIPresShell *presShell = PresContext()->GetPresShell();
if (presShell) {
presShell->FrameNeedsReflow(this, nsIPresShell::eStyleChange,
NS_FRAME_IS_DIRTY);
}
}
// Update border+content to account for image change
InvalidateFrame();
}
}
nsresult
nsImageFrame::FrameChanged(imgIRequest *aRequest,
imgIContainer *aContainer)
{
if (!GetStyleVisibility()->IsVisible()) {
return NS_OK;
}
if (IsPendingLoad(aContainer)) {
// We don't care about it
return NS_OK;
}
InvalidateLayer(nsDisplayItem::TYPE_IMAGE);
return NS_OK;
}
void
nsImageFrame::EnsureIntrinsicSizeAndRatio(nsPresContext* aPresContext)
{
// if mIntrinsicSize.width and height are 0, then we should
// check to see if the size is already known by the image container.
if (mIntrinsicSize.width.GetUnit() == eStyleUnit_Coord &&
mIntrinsicSize.width.GetCoordValue() == 0 &&
mIntrinsicSize.height.GetUnit() == eStyleUnit_Coord &&
mIntrinsicSize.height.GetCoordValue() == 0) {
// Jump through all the hoops to get the status of the request
nsCOMPtr<imgIRequest> currentRequest;
nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
if (imageLoader)
imageLoader->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
getter_AddRefs(currentRequest));
uint32_t status = 0;
if (currentRequest)
currentRequest->GetImageStatus(&status);
// If we know the size, we can grab it and use it for an update
if (status & imgIRequest::STATUS_SIZE_AVAILABLE) {
nsCOMPtr<imgIContainer> imgCon;
currentRequest->GetImage(getter_AddRefs(imgCon));
NS_ABORT_IF_FALSE(imgCon, "SIZE_AVAILABLE, but no imgContainer?");
UpdateIntrinsicSize(imgCon);
UpdateIntrinsicRatio(imgCon);
} else {
// image request is null or image size not known, probably an
// invalid image specified
// - make the image big enough for the icon (it may not be
// used if inline alt expansion is used instead)
// XXX: we need this in composer, but it is also good for
// XXX: general quirks mode to always have room for the icon
if (aPresContext->CompatibilityMode() == eCompatibility_NavQuirks) {
nscoord edgeLengthToUse =
nsPresContext::CSSPixelsToAppUnits(
ICON_SIZE + (2 * (ICON_PADDING + ALT_BORDER_WIDTH)));
mIntrinsicSize.width.SetCoordValue(edgeLengthToUse);
mIntrinsicSize.height.SetCoordValue(edgeLengthToUse);
mIntrinsicRatio.SizeTo(1, 1);
}
}
}
}
/* virtual */ nsSize
nsImageFrame::ComputeSize(nsRenderingContext *aRenderingContext,
nsSize aCBSize, nscoord aAvailableWidth,
nsSize aMargin, nsSize aBorder, nsSize aPadding,
uint32_t aFlags)
{
nsPresContext *presContext = PresContext();
EnsureIntrinsicSizeAndRatio(presContext);
return nsLayoutUtils::ComputeSizeWithIntrinsicDimensions(
aRenderingContext, this,
mIntrinsicSize, mIntrinsicRatio, aCBSize,
aMargin, aBorder, aPadding);
}
nsRect
nsImageFrame::GetInnerArea() const
{
return GetContentRect() - GetPosition();
}
// get the offset into the content area of the image where aImg starts if it is a continuation.
nscoord
nsImageFrame::GetContinuationOffset() const
{
nscoord offset = 0;
for (nsIFrame *f = GetPrevInFlow(); f; f = f->GetPrevInFlow()) {
offset += f->GetContentRect().height;
}
NS_ASSERTION(offset >= 0, "bogus GetContentRect");
return offset;
}
/* virtual */ nscoord
nsImageFrame::GetMinWidth(nsRenderingContext *aRenderingContext)
{
// XXX The caller doesn't account for constraints of the height,
// min-height, and max-height properties.
DebugOnly<nscoord> result;
DISPLAY_MIN_WIDTH(this, result);
nsPresContext *presContext = PresContext();
EnsureIntrinsicSizeAndRatio(presContext);
return mIntrinsicSize.width.GetUnit() == eStyleUnit_Coord ?
mIntrinsicSize.width.GetCoordValue() : 0;
}
/* virtual */ nscoord
nsImageFrame::GetPrefWidth(nsRenderingContext *aRenderingContext)
{
// XXX The caller doesn't account for constraints of the height,
// min-height, and max-height properties.
DebugOnly<nscoord> result;
DISPLAY_PREF_WIDTH(this, result);
nsPresContext *presContext = PresContext();
EnsureIntrinsicSizeAndRatio(presContext);
// convert from normal twips to scaled twips (printing...)
return mIntrinsicSize.width.GetUnit() == eStyleUnit_Coord ?
mIntrinsicSize.width.GetCoordValue() : 0;
}
/* virtual */ nsIFrame::IntrinsicSize
nsImageFrame::GetIntrinsicSize()
{
return mIntrinsicSize;
}
/* virtual */ nsSize
nsImageFrame::GetIntrinsicRatio()
{
return mIntrinsicRatio;
}
NS_IMETHODIMP
nsImageFrame::Reflow(nsPresContext* aPresContext,
nsHTMLReflowMetrics& aMetrics,
const nsHTMLReflowState& aReflowState,
nsReflowStatus& aStatus)
{
DO_GLOBAL_REFLOW_COUNT("nsImageFrame");
DISPLAY_REFLOW(aPresContext, this, aReflowState, aMetrics, aStatus);
NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS,
("enter nsImageFrame::Reflow: availSize=%d,%d",
aReflowState.availableWidth, aReflowState.availableHeight));
NS_PRECONDITION(mState & NS_FRAME_IN_REFLOW, "frame is not in reflow");
aStatus = NS_FRAME_COMPLETE;
// see if we have a frozen size (i.e. a fixed width and height)
if (HaveFixedSize(aReflowState)) {
mState |= IMAGE_SIZECONSTRAINED;
} else {
mState &= ~IMAGE_SIZECONSTRAINED;
}
// XXXldb These two bits are almost exact opposites (except in the
// middle of the initial reflow); remove IMAGE_GOTINITIALREFLOW.
if (GetStateBits() & NS_FRAME_FIRST_REFLOW) {
mState |= IMAGE_GOTINITIALREFLOW;
}
mComputedSize =
nsSize(aReflowState.ComputedWidth(), aReflowState.ComputedHeight());
aMetrics.width = mComputedSize.width;
aMetrics.height = mComputedSize.height;
// add borders and padding
aMetrics.width += aReflowState.mComputedBorderPadding.LeftRight();
aMetrics.height += aReflowState.mComputedBorderPadding.TopBottom();
if (GetPrevInFlow()) {
aMetrics.width = GetPrevInFlow()->GetSize().width;
nscoord y = GetContinuationOffset();
aMetrics.height -= y + aReflowState.mComputedBorderPadding.top;
aMetrics.height = NS_MAX(0, aMetrics.height);
}
// we have to split images if we are:
// in Paginated mode, we need to have a constrained height, and have a height larger than our available height
uint32_t loadStatus = imgIRequest::STATUS_NONE;
nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
NS_ASSERTION(imageLoader, "No content node??");
if (imageLoader) {
nsCOMPtr<imgIRequest> currentRequest;
imageLoader->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
getter_AddRefs(currentRequest));
if (currentRequest) {
currentRequest->GetImageStatus(&loadStatus);
}
}
if (aPresContext->IsPaginated() &&
((loadStatus & imgIRequest::STATUS_SIZE_AVAILABLE) || (mState & IMAGE_SIZECONSTRAINED)) &&
NS_UNCONSTRAINEDSIZE != aReflowState.availableHeight &&
aMetrics.height > aReflowState.availableHeight) {
// our desired height was greater than 0, so to avoid infinite
// splitting, use 1 pixel as the min
aMetrics.height = NS_MAX(nsPresContext::CSSPixelsToAppUnits(1), aReflowState.availableHeight);
aStatus = NS_FRAME_NOT_COMPLETE;
}
aMetrics.SetOverflowAreasToDesiredBounds();
nsEventStates contentState = mContent->AsElement()->State();
bool imageOK = IMAGE_OK(contentState, true);
// Determine if the size is available
bool haveSize = false;
if (loadStatus & imgIRequest::STATUS_SIZE_AVAILABLE) {
haveSize = true;
}
if (!imageOK || !haveSize) {
nsRect altFeedbackSize(0, 0,
nsPresContext::CSSPixelsToAppUnits(ICON_SIZE+2*(ICON_PADDING+ALT_BORDER_WIDTH)),
nsPresContext::CSSPixelsToAppUnits(ICON_SIZE+2*(ICON_PADDING+ALT_BORDER_WIDTH)));
// We include the altFeedbackSize in our visual overflow, but not in our
// scrollable overflow, since it doesn't really need to be scrolled to
// outside the image.
MOZ_STATIC_ASSERT(eOverflowType_LENGTH == 2, "Unknown overflow types?");
nsRect& visualOverflow = aMetrics.VisualOverflow();
visualOverflow.UnionRect(visualOverflow, altFeedbackSize);
}
FinishAndStoreOverflow(&aMetrics);
NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS,
("exit nsImageFrame::Reflow: size=%d,%d",
aMetrics.width, aMetrics.height));
NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aMetrics);
return NS_OK;
}
// Computes the width of the specified string. aMaxWidth specifies the maximum
// width available. Once this limit is reached no more characters are measured.
// The number of characters that fit within the maximum width are returned in
// aMaxFit. NOTE: it is assumed that the fontmetrics have already been selected
// into the rendering context before this is called (for performance). MMP
nscoord
nsImageFrame::MeasureString(const PRUnichar* aString,
int32_t aLength,
nscoord aMaxWidth,
uint32_t& aMaxFit,
nsRenderingContext& aContext)
{
nscoord totalWidth = 0;
aContext.SetTextRunRTL(false);
nscoord spaceWidth = aContext.GetWidth(' ');
aMaxFit = 0;
while (aLength > 0) {
// Find the next place we can line break
uint32_t len = aLength;
bool trailingSpace = false;
for (int32_t i = 0; i < aLength; i++) {
if (dom::IsSpaceCharacter(aString[i]) && (i > 0)) {
len = i; // don't include the space when measuring
trailingSpace = true;
break;
}
}
// Measure this chunk of text, and see if it fits
nscoord width =
nsLayoutUtils::GetStringWidth(this, &aContext, aString, len);
bool fits = (totalWidth + width) <= aMaxWidth;
// If it fits on the line, or it's the first word we've processed then
// include it
if (fits || (0 == totalWidth)) {
// New piece fits
totalWidth += width;
// If there's a trailing space then see if it fits as well
if (trailingSpace) {
if ((totalWidth + spaceWidth) <= aMaxWidth) {
totalWidth += spaceWidth;
} else {
// Space won't fit. Leave it at the end but don't include it in
// the width
fits = false;
}
len++;
}
aMaxFit += len;
aString += len;
aLength -= len;
}
if (!fits) {
break;
}
}
return totalWidth;
}
// Formats the alt-text to fit within the specified rectangle. Breaks lines
// between words if a word would extend past the edge of the rectangle
void
nsImageFrame::DisplayAltText(nsPresContext* aPresContext,
nsRenderingContext& aRenderingContext,
const nsString& aAltText,
const nsRect& aRect)
{
// Set font and color
aRenderingContext.SetColor(GetStyleColor()->mColor);
nsRefPtr<nsFontMetrics> fm;
nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
nsLayoutUtils::FontSizeInflationFor(this));