forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsImageLoadingContent.cpp
1593 lines (1358 loc) · 47.1 KB
/
nsImageLoadingContent.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 -*- */
// vim: ft=cpp tw=78 sw=2 et ts=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/. */
/*
* A base class which implements nsIImageLoadingContent and can be
* subclassed by various content nodes that want to provide image
* loading functionality (eg <img>, <object>, etc).
*/
#include "nsImageLoadingContent.h"
#include "nsAutoPtr.h"
#include "nsError.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsIScriptGlobalObject.h"
#include "nsIDOMWindow.h"
#include "nsServiceManagerUtils.h"
#include "nsContentPolicyUtils.h"
#include "nsIURI.h"
#include "nsILoadGroup.h"
#include "imgIContainer.h"
#include "imgLoader.h"
#include "imgRequestProxy.h"
#include "nsThreadUtils.h"
#include "nsNetUtil.h"
#include "nsImageFrame.h"
#include "nsIPresShell.h"
#include "nsIChannel.h"
#include "nsIStreamListener.h"
#include "nsIFrame.h"
#include "nsIDOMNode.h"
#include "nsContentUtils.h"
#include "nsLayoutUtils.h"
#include "nsIContentPolicy.h"
#include "nsSVGEffects.h"
#include "mozAutoDocUpdate.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/EventStates.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ScriptSettings.h"
#ifdef LoadImage
// Undefine LoadImage to prevent naming conflict with Windows.
#undef LoadImage
#endif
using namespace mozilla;
#ifdef DEBUG_chb
static void PrintReqURL(imgIRequest* req) {
if (!req) {
printf("(null req)\n");
return;
}
nsCOMPtr<nsIURI> uri;
req->GetURI(getter_AddRefs(uri));
if (!uri) {
printf("(null uri)\n");
return;
}
nsAutoCString spec;
uri->GetSpec(spec);
printf("spec='%s'\n", spec.get());
}
#endif /* DEBUG_chb */
nsImageLoadingContent::nsImageLoadingContent()
: mCurrentRequestFlags(0),
mPendingRequestFlags(0),
mObserverList(nullptr),
mImageBlockingStatus(nsIContentPolicy::ACCEPT),
mLoadingEnabled(true),
mIsImageStateForced(false),
mLoading(false),
// mBroken starts out true, since an image without a URI is broken....
mBroken(true),
mUserDisabled(false),
mSuppressed(false),
mFireEventsOnDecode(false),
mNewRequestsWillNeedAnimationReset(false),
mStateChangerDepth(0),
mCurrentRequestRegistered(false),
mPendingRequestRegistered(false),
mFrameCreateCalled(false),
mVisibleCount(0)
{
if (!nsContentUtils::GetImgLoaderForChannel(nullptr, nullptr)) {
mLoadingEnabled = false;
}
}
void
nsImageLoadingContent::DestroyImageLoadingContent()
{
// Cancel our requests so they won't hold stale refs to us
// NB: Don't ask to discard the images here.
ClearCurrentRequest(NS_BINDING_ABORTED, ON_NONVISIBLE_NO_ACTION);
ClearPendingRequest(NS_BINDING_ABORTED, ON_NONVISIBLE_NO_ACTION);
}
nsImageLoadingContent::~nsImageLoadingContent()
{
NS_ASSERTION(!mCurrentRequest && !mPendingRequest,
"DestroyImageLoadingContent not called");
NS_ASSERTION(!mObserverList.mObserver && !mObserverList.mNext,
"Observers still registered?");
}
/*
* imgINotificationObserver impl
*/
NS_IMETHODIMP
nsImageLoadingContent::Notify(imgIRequest* aRequest,
int32_t aType,
const nsIntRect* aData)
{
if (aType == imgINotificationObserver::IS_ANIMATED) {
return OnImageIsAnimated(aRequest);
}
if (aType == imgINotificationObserver::UNLOCKED_DRAW) {
OnUnlockedDraw();
return NS_OK;
}
if (aType == imgINotificationObserver::LOAD_COMPLETE) {
// We should definitely have a request here
NS_ABORT_IF_FALSE(aRequest, "no request?");
NS_PRECONDITION(aRequest == mCurrentRequest || aRequest == mPendingRequest,
"Unknown request");
}
{
nsAutoScriptBlocker scriptBlocker;
for (ImageObserver* observer = &mObserverList, *next; observer;
observer = next) {
next = observer->mNext;
if (observer->mObserver) {
observer->mObserver->Notify(aRequest, aType, aData);
}
}
}
if (aType == imgINotificationObserver::SIZE_AVAILABLE) {
// Have to check for state changes here, since we might have been in
// the LOADING state before.
UpdateImageState(true);
}
if (aType == imgINotificationObserver::LOAD_COMPLETE) {
uint32_t reqStatus;
aRequest->GetImageStatus(&reqStatus);
/* triage STATUS_ERROR */
if (reqStatus & imgIRequest::STATUS_ERROR) {
nsresult errorCode = NS_OK;
aRequest->GetImageErrorCode(&errorCode);
/* Handle image not loading error because source was a tracking URL.
* We make a note of this image node by including it in a dedicated
* array of blocked tracking nodes under its parent document.
*/
if (errorCode == NS_ERROR_TRACKING_URI) {
nsCOMPtr<nsIContent> thisNode
= do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
nsIDocument *doc = GetOurOwnerDoc();
doc->AddBlockedTrackingNode(thisNode);
}
}
nsresult status =
reqStatus & imgIRequest::STATUS_ERROR ? NS_ERROR_FAILURE : NS_OK;
return OnLoadComplete(aRequest, status);
}
if (aType == imgINotificationObserver::DECODE_COMPLETE) {
if (mFireEventsOnDecode) {
mFireEventsOnDecode = false;
uint32_t reqStatus;
aRequest->GetImageStatus(&reqStatus);
if (reqStatus & imgIRequest::STATUS_ERROR) {
FireEvent(NS_LITERAL_STRING("error"));
} else {
FireEvent(NS_LITERAL_STRING("load"));
}
}
UpdateImageState(true);
}
return NS_OK;
}
nsresult
nsImageLoadingContent::OnLoadComplete(imgIRequest* aRequest, nsresult aStatus)
{
uint32_t oldStatus;
aRequest->GetImageStatus(&oldStatus);
//XXXjdm This occurs when we have a pending request created, then another
// pending request replaces it before the first one is finished.
// This begs the question of what the correct behaviour is; we used
// to not have to care because we ran this code in OnStopDecode which
// wasn't called when the first request was cancelled. For now, I choose
// to punt when the given request doesn't appear to have terminated in
// an expected state.
if (!(oldStatus & (imgIRequest::STATUS_ERROR | imgIRequest::STATUS_LOAD_COMPLETE)))
return NS_OK;
// Our state may change. Watch it.
AutoStateChanger changer(this, true);
// If the pending request is loaded, switch to it.
if (aRequest == mPendingRequest) {
MakePendingRequestCurrent();
}
NS_ABORT_IF_FALSE(aRequest == mCurrentRequest,
"One way or another, we should be current by now");
// We just loaded all the data we're going to get. If we're visible and
// haven't done an initial paint (*), we want to make sure the image starts
// decoding immediately, for two reasons:
//
// 1) This image is sitting idle but might need to be decoded as soon as we
// start painting, in which case we've wasted time.
//
// 2) We want to block onload until all visible images are decoded. We do this
// by blocking onload until all in-progress decodes get at least one frame
// decoded. However, if all the data comes in while painting is suppressed
// (ie, before the initial paint delay is finished), we fire onload without
// doing a paint first. This means that decode-on-draw images don't start
// decoding, so we can't wait for them to finish. See bug 512435.
//
// (*) IsPaintingSuppressed returns false if we haven't gotten the initial
// reflow yet, so we have to test !DidInitialize || IsPaintingSuppressed.
// It's possible for painting to be suppressed for reasons other than the
// initial paint delay (for example, being in the bfcache), but we probably
// aren't loading images in those situations.
// XXXkhuey should this be GetOurCurrentDoc? Decoding if we're not in
// the document seems silly.
nsIDocument* doc = GetOurOwnerDoc();
nsIPresShell* shell = doc ? doc->GetShell() : nullptr;
if (shell && shell->IsVisible() &&
(!shell->DidInitialize() || shell->IsPaintingSuppressed())) {
nsIFrame* f = GetOurPrimaryFrame();
// If we haven't gotten a frame yet either we aren't going to (so don't
// bother kicking off a decode), or we will get very soon on the next
// refresh driver tick when it flushes. And it will most likely be a
// specific image type frame (we only create generic (ie inline) type
// frames for images that don't have a size, and since we have all the data
// we should have the size) which will check its own visibility on its
// first reflow.
if (f) {
// If we've gotten a frame and that frame has called FrameCreate and that
// frame has been reflowed then we know that it checked it's own visibility
// so we can trust our visible count and we don't start decode if we are not
// visible.
if (!mFrameCreateCalled || (f->GetStateBits() & NS_FRAME_FIRST_REFLOW) ||
mVisibleCount > 0 || shell->AssumeAllImagesVisible()) {
mCurrentRequest->StartDecoding();
}
}
}
// We want to give the decoder a chance to find errors. If we haven't found
// an error yet and we've started decoding, either from the above
// StartDecoding or from some other place, we must only fire these events
// after we finish decoding.
uint32_t reqStatus;
aRequest->GetImageStatus(&reqStatus);
if (NS_SUCCEEDED(aStatus) && !(reqStatus & imgIRequest::STATUS_ERROR) &&
(reqStatus & imgIRequest::STATUS_DECODE_STARTED) &&
!(reqStatus & imgIRequest::STATUS_DECODE_COMPLETE)) {
mFireEventsOnDecode = true;
} else {
// Fire the appropriate DOM event.
if (NS_SUCCEEDED(aStatus)) {
FireEvent(NS_LITERAL_STRING("load"));
} else {
FireEvent(NS_LITERAL_STRING("error"));
}
}
nsCOMPtr<nsINode> thisNode = do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
nsSVGEffects::InvalidateDirectRenderingObservers(thisNode->AsElement());
return NS_OK;
}
static bool
ImageIsAnimated(imgIRequest* aRequest)
{
if (!aRequest) {
return false;
}
nsCOMPtr<imgIContainer> image;
if (NS_SUCCEEDED(aRequest->GetImage(getter_AddRefs(image)))) {
bool isAnimated = false;
nsresult rv = image->GetAnimated(&isAnimated);
if (NS_SUCCEEDED(rv) && isAnimated) {
return true;
}
}
return false;
}
void
nsImageLoadingContent::OnUnlockedDraw()
{
if (mVisibleCount > 0) {
// We should already be marked as visible, there is nothing more we can do.
return;
}
// It's OK for non-animated images to wait until the next image visibility
// update to become locked. (And that's preferable, since in the case of
// scrolling it keeps memory usage minimal.) For animated images, though, we
// want to mark them visible right away so we can call
// IncrementAnimationConsumers() on them and they'll start animating.
if (!ImageIsAnimated(mCurrentRequest) && !ImageIsAnimated(mPendingRequest)) {
return;
}
nsPresContext* presContext = GetFramePresContext();
if (!presContext)
return;
nsIPresShell* presShell = presContext->PresShell();
if (!presShell)
return;
presShell->EnsureImageInVisibleList(this);
}
nsresult
nsImageLoadingContent::OnImageIsAnimated(imgIRequest *aRequest)
{
bool* requestFlag = GetRegisteredFlagForRequest(aRequest);
if (requestFlag) {
nsLayoutUtils::RegisterImageRequest(GetFramePresContext(),
aRequest, requestFlag);
}
return NS_OK;
}
/*
* nsIImageLoadingContent impl
*/
NS_IMETHODIMP
nsImageLoadingContent::GetLoadingEnabled(bool *aLoadingEnabled)
{
*aLoadingEnabled = mLoadingEnabled;
return NS_OK;
}
NS_IMETHODIMP
nsImageLoadingContent::SetLoadingEnabled(bool aLoadingEnabled)
{
if (nsContentUtils::GetImgLoaderForChannel(nullptr, nullptr)) {
mLoadingEnabled = aLoadingEnabled;
}
return NS_OK;
}
NS_IMETHODIMP
nsImageLoadingContent::GetImageBlockingStatus(int16_t* aStatus)
{
NS_PRECONDITION(aStatus, "Null out param");
*aStatus = ImageBlockingStatus();
return NS_OK;
}
static void
ReplayImageStatus(imgIRequest* aRequest, imgINotificationObserver* aObserver)
{
if (!aRequest) {
return;
}
uint32_t status = 0;
nsresult rv = aRequest->GetImageStatus(&status);
if (NS_FAILED(rv)) {
return;
}
if (status & imgIRequest::STATUS_SIZE_AVAILABLE) {
aObserver->Notify(aRequest, imgINotificationObserver::SIZE_AVAILABLE, nullptr);
}
if (status & imgIRequest::STATUS_FRAME_COMPLETE) {
aObserver->Notify(aRequest, imgINotificationObserver::FRAME_COMPLETE, nullptr);
}
if (status & imgIRequest::STATUS_HAS_TRANSPARENCY) {
aObserver->Notify(aRequest, imgINotificationObserver::HAS_TRANSPARENCY, nullptr);
}
if (status & imgIRequest::STATUS_IS_ANIMATED) {
aObserver->Notify(aRequest, imgINotificationObserver::IS_ANIMATED, nullptr);
}
if (status & imgIRequest::STATUS_DECODE_COMPLETE) {
aObserver->Notify(aRequest, imgINotificationObserver::DECODE_COMPLETE, nullptr);
}
if (status & imgIRequest::STATUS_LOAD_COMPLETE) {
aObserver->Notify(aRequest, imgINotificationObserver::LOAD_COMPLETE, nullptr);
}
}
NS_IMETHODIMP
nsImageLoadingContent::AddObserver(imgINotificationObserver* aObserver)
{
NS_ENSURE_ARG_POINTER(aObserver);
if (!mObserverList.mObserver) {
// Don't touch the linking of the list!
mObserverList.mObserver = aObserver;
ReplayImageStatus(mCurrentRequest, aObserver);
ReplayImageStatus(mPendingRequest, aObserver);
return NS_OK;
}
// otherwise we have to create a new entry
ImageObserver* observer = &mObserverList;
while (observer->mNext) {
observer = observer->mNext;
}
observer->mNext = new ImageObserver(aObserver);
if (! observer->mNext) {
return NS_ERROR_OUT_OF_MEMORY;
}
ReplayImageStatus(mCurrentRequest, aObserver);
ReplayImageStatus(mPendingRequest, aObserver);
return NS_OK;
}
NS_IMETHODIMP
nsImageLoadingContent::RemoveObserver(imgINotificationObserver* aObserver)
{
NS_ENSURE_ARG_POINTER(aObserver);
if (mObserverList.mObserver == aObserver) {
mObserverList.mObserver = nullptr;
// Don't touch the linking of the list!
return NS_OK;
}
// otherwise have to find it and splice it out
ImageObserver* observer = &mObserverList;
while (observer->mNext && observer->mNext->mObserver != aObserver) {
observer = observer->mNext;
}
// At this point, we are pointing to the list element whose mNext is
// the right observer (assuming of course that mNext is not null)
if (observer->mNext) {
// splice it out
ImageObserver* oldObserver = observer->mNext;
observer->mNext = oldObserver->mNext;
oldObserver->mNext = nullptr; // so we don't destroy them all
delete oldObserver;
}
#ifdef DEBUG
else {
NS_WARNING("Asked to remove nonexistent observer");
}
#endif
return NS_OK;
}
already_AddRefed<imgIRequest>
nsImageLoadingContent::GetRequest(int32_t aRequestType,
ErrorResult& aError)
{
nsCOMPtr<imgIRequest> request;
switch(aRequestType) {
case CURRENT_REQUEST:
request = mCurrentRequest;
break;
case PENDING_REQUEST:
request = mPendingRequest;
break;
default:
NS_ERROR("Unknown request type");
aError.Throw(NS_ERROR_UNEXPECTED);
}
return request.forget();
}
NS_IMETHODIMP
nsImageLoadingContent::GetRequest(int32_t aRequestType,
imgIRequest** aRequest)
{
NS_ENSURE_ARG_POINTER(aRequest);
ErrorResult result;
*aRequest = GetRequest(aRequestType, result).take();
return result.ErrorCode();
}
NS_IMETHODIMP_(bool)
nsImageLoadingContent::CurrentRequestHasSize()
{
return HaveSize(mCurrentRequest);
}
NS_IMETHODIMP_(void)
nsImageLoadingContent::FrameCreated(nsIFrame* aFrame)
{
NS_ASSERTION(aFrame, "aFrame is null");
mFrameCreateCalled = true;
if (aFrame->HasAnyStateBits(NS_FRAME_IN_POPUP)) {
// Assume all images in popups are visible.
IncrementVisibleCount();
}
TrackImage(mCurrentRequest);
TrackImage(mPendingRequest);
// We need to make sure that our image request is registered, if it should
// be registered.
nsPresContext* presContext = aFrame->PresContext();
if (mCurrentRequest) {
nsLayoutUtils::RegisterImageRequestIfAnimated(presContext, mCurrentRequest,
&mCurrentRequestRegistered);
}
if (mPendingRequest) {
nsLayoutUtils::RegisterImageRequestIfAnimated(presContext, mPendingRequest,
&mPendingRequestRegistered);
}
}
NS_IMETHODIMP_(void)
nsImageLoadingContent::FrameDestroyed(nsIFrame* aFrame)
{
NS_ASSERTION(aFrame, "aFrame is null");
mFrameCreateCalled = false;
// We need to make sure that our image request is deregistered.
nsPresContext* presContext = GetFramePresContext();
if (mCurrentRequest) {
nsLayoutUtils::DeregisterImageRequest(presContext,
mCurrentRequest,
&mCurrentRequestRegistered);
}
if (mPendingRequest) {
nsLayoutUtils::DeregisterImageRequest(presContext,
mPendingRequest,
&mPendingRequestRegistered);
}
UntrackImage(mCurrentRequest);
UntrackImage(mPendingRequest);
nsIPresShell* presShell = presContext ? presContext->GetPresShell() : nullptr;
if (presShell) {
presShell->RemoveImageFromVisibleList(this);
}
if (aFrame->HasAnyStateBits(NS_FRAME_IN_POPUP)) {
// We assume all images in popups are visible, so this decrement balances
// out the increment in FrameCreated above.
DecrementVisibleCount(ON_NONVISIBLE_NO_ACTION);
}
}
/* static */
nsContentPolicyType
nsImageLoadingContent::PolicyTypeForLoad(ImageLoadType aImageLoadType)
{
if (aImageLoadType == eImageLoadType_Imageset) {
return nsIContentPolicy::TYPE_IMAGESET;
}
MOZ_ASSERT(aImageLoadType == eImageLoadType_Normal,
"Unknown ImageLoadType type in PolicyTypeForLoad");
return nsIContentPolicy::TYPE_IMAGE;
}
int32_t
nsImageLoadingContent::GetRequestType(imgIRequest* aRequest,
ErrorResult& aError)
{
if (aRequest == mCurrentRequest) {
return CURRENT_REQUEST;
}
if (aRequest == mPendingRequest) {
return PENDING_REQUEST;
}
NS_ERROR("Unknown request");
aError.Throw(NS_ERROR_UNEXPECTED);
return UNKNOWN_REQUEST;
}
NS_IMETHODIMP
nsImageLoadingContent::GetRequestType(imgIRequest* aRequest,
int32_t* aRequestType)
{
NS_PRECONDITION(aRequestType, "Null out param");
ErrorResult result;
*aRequestType = GetRequestType(aRequest, result);
return result.ErrorCode();
}
already_AddRefed<nsIURI>
nsImageLoadingContent::GetCurrentURI(ErrorResult& aError)
{
nsCOMPtr<nsIURI> uri;
if (mCurrentRequest) {
mCurrentRequest->GetURI(getter_AddRefs(uri));
} else if (mCurrentURI) {
nsresult rv = NS_EnsureSafeToReturn(mCurrentURI, getter_AddRefs(uri));
if (NS_FAILED(rv)) {
aError.Throw(rv);
}
}
return uri.forget();
}
NS_IMETHODIMP
nsImageLoadingContent::GetCurrentURI(nsIURI** aURI)
{
NS_ENSURE_ARG_POINTER(aURI);
ErrorResult result;
*aURI = GetCurrentURI(result).take();
return result.ErrorCode();
}
already_AddRefed<nsIStreamListener>
nsImageLoadingContent::LoadImageWithChannel(nsIChannel* aChannel,
ErrorResult& aError)
{
imgLoader* loader =
nsContentUtils::GetImgLoaderForChannel(aChannel, GetOurOwnerDoc());
if (!loader) {
aError.Throw(NS_ERROR_NULL_POINTER);
return nullptr;
}
nsCOMPtr<nsIDocument> doc = GetOurOwnerDoc();
if (!doc) {
// Don't bother
return nullptr;
}
// XXX what should we do with content policies here, if anything?
// Shouldn't that be done before the start of the load?
// XXX what about shouldProcess?
// Our state might change. Watch it.
AutoStateChanger changer(this, true);
// Do the load.
nsCOMPtr<nsIStreamListener> listener;
nsRefPtr<imgRequestProxy>& req = PrepareNextRequest(eImageLoadType_Normal);
nsresult rv = loader->
LoadImageWithChannel(aChannel, this, doc,
getter_AddRefs(listener),
getter_AddRefs(req));
if (NS_SUCCEEDED(rv)) {
TrackImage(req);
ResetAnimationIfNeeded();
} else {
MOZ_ASSERT(!req, "Shouldn't have non-null request here");
// If we don't have a current URI, we might as well store this URI so people
// know what we tried (and failed) to load.
if (!mCurrentRequest)
aChannel->GetURI(getter_AddRefs(mCurrentURI));
FireEvent(NS_LITERAL_STRING("error"));
aError.Throw(rv);
}
return listener.forget();
}
NS_IMETHODIMP
nsImageLoadingContent::LoadImageWithChannel(nsIChannel* aChannel,
nsIStreamListener** aListener)
{
NS_ENSURE_ARG_POINTER(aListener);
ErrorResult result;
*aListener = LoadImageWithChannel(aChannel, result).take();
return result.ErrorCode();
}
void
nsImageLoadingContent::ForceReload(const mozilla::dom::Optional<bool>& aNotify,
mozilla::ErrorResult& aError)
{
nsCOMPtr<nsIURI> currentURI;
GetCurrentURI(getter_AddRefs(currentURI));
if (!currentURI) {
aError.Throw(NS_ERROR_NOT_AVAILABLE);
return;
}
// defaults to true
bool notify = !aNotify.WasPassed() || aNotify.Value();
// We keep this flag around along with the old URI even for failed requests
// without a live request object
ImageLoadType loadType = \
(mCurrentRequestFlags & REQUEST_IS_IMAGESET) ? eImageLoadType_Imageset
: eImageLoadType_Normal;
nsresult rv = LoadImage(currentURI, true, notify, loadType, nullptr,
nsIRequest::VALIDATE_ALWAYS);
if (NS_FAILED(rv)) {
aError.Throw(rv);
}
}
NS_IMETHODIMP
nsImageLoadingContent::ForceReload(bool aNotify /* = true */,
uint8_t aArgc)
{
mozilla::dom::Optional<bool> notify;
if (aArgc >= 1) {
notify.Construct() = aNotify;
}
ErrorResult result;
ForceReload(notify, result);
return result.ErrorCode();
}
NS_IMETHODIMP
nsImageLoadingContent::BlockOnload(imgIRequest* aRequest)
{
if (aRequest == mCurrentRequest) {
NS_ASSERTION(!(mCurrentRequestFlags & REQUEST_BLOCKS_ONLOAD),
"Double BlockOnload!?");
mCurrentRequestFlags |= REQUEST_BLOCKS_ONLOAD;
} else if (aRequest == mPendingRequest) {
NS_ASSERTION(!(mPendingRequestFlags & REQUEST_BLOCKS_ONLOAD),
"Double BlockOnload!?");
mPendingRequestFlags |= REQUEST_BLOCKS_ONLOAD;
} else {
return NS_OK;
}
nsIDocument* doc = GetOurCurrentDoc();
if (doc) {
doc->BlockOnload();
}
return NS_OK;
}
NS_IMETHODIMP
nsImageLoadingContent::UnblockOnload(imgIRequest* aRequest)
{
if (aRequest == mCurrentRequest) {
NS_ASSERTION(mCurrentRequestFlags & REQUEST_BLOCKS_ONLOAD,
"Double UnblockOnload!?");
mCurrentRequestFlags &= ~REQUEST_BLOCKS_ONLOAD;
} else if (aRequest == mPendingRequest) {
NS_ASSERTION(mPendingRequestFlags & REQUEST_BLOCKS_ONLOAD,
"Double UnblockOnload!?");
mPendingRequestFlags &= ~REQUEST_BLOCKS_ONLOAD;
} else {
return NS_OK;
}
nsIDocument* doc = GetOurCurrentDoc();
if (doc) {
doc->UnblockOnload(false);
}
return NS_OK;
}
void
nsImageLoadingContent::IncrementVisibleCount()
{
mVisibleCount++;
if (mVisibleCount == 1) {
TrackImage(mCurrentRequest);
TrackImage(mPendingRequest);
}
}
void
nsImageLoadingContent::DecrementVisibleCount(uint32_t aNonvisibleAction)
{
NS_ASSERTION(mVisibleCount > 0, "visible count should be positive here");
mVisibleCount--;
if (mVisibleCount == 0) {
UntrackImage(mCurrentRequest, aNonvisibleAction);
UntrackImage(mPendingRequest, aNonvisibleAction);
}
}
uint32_t
nsImageLoadingContent::GetVisibleCount()
{
return mVisibleCount;
}
/*
* Non-interface methods
*/
nsresult
nsImageLoadingContent::LoadImage(const nsAString& aNewURI,
bool aForce,
bool aNotify,
ImageLoadType aImageLoadType)
{
// First, get a document (needed for security checks and the like)
nsIDocument* doc = GetOurOwnerDoc();
if (!doc) {
// No reason to bother, I think...
return NS_OK;
}
nsCOMPtr<nsIURI> imageURI;
nsresult rv = StringToURI(aNewURI, doc, getter_AddRefs(imageURI));
NS_ENSURE_SUCCESS(rv, rv);
// XXXbiesi fire onerror if that failed?
bool equal;
if (aNewURI.IsEmpty() &&
doc->GetDocumentURI() &&
NS_SUCCEEDED(doc->GetDocumentURI()->EqualsExceptRef(imageURI, &equal)) &&
equal) {
// Loading an embedded img from the same URI as the document URI will not work
// as a resource cannot recursively embed itself. Attempting to do so generally
// results in having to pre-emptively close down an in-flight HTTP transaction
// and then incurring the significant cost of establishing a new TCP channel.
// This is generally triggered from <img src="">
// In light of that, just skip loading it..
// Do make sure to drop our existing image, if any
CancelImageRequests(aNotify);
return NS_OK;
}
NS_TryToSetImmutable(imageURI);
return LoadImage(imageURI, aForce, aNotify, aImageLoadType, doc);
}
nsresult
nsImageLoadingContent::LoadImage(nsIURI* aNewURI,
bool aForce,
bool aNotify,
ImageLoadType aImageLoadType,
nsIDocument* aDocument,
nsLoadFlags aLoadFlags)
{
if (!mLoadingEnabled) {
// XXX Why fire an error here? seems like the callers to SetLoadingEnabled
// don't want/need it.
FireEvent(NS_LITERAL_STRING("error"));
return NS_OK;
}
NS_ASSERTION(!aDocument || aDocument == GetOurOwnerDoc(),
"Bogus document passed in");
// First, get a document (needed for security checks and the like)
if (!aDocument) {
aDocument = GetOurOwnerDoc();
if (!aDocument) {
// No reason to bother, I think...
return NS_OK;
}
}
// URI equality check.
//
// We skip the equality check if our current image was blocked, since in that
// case we really do want to try loading again.
if (!aForce && NS_CP_ACCEPTED(mImageBlockingStatus)) {
nsCOMPtr<nsIURI> currentURI;
GetCurrentURI(getter_AddRefs(currentURI));
bool equal;
if (currentURI &&
NS_SUCCEEDED(currentURI->Equals(aNewURI, &equal)) &&
equal) {
// Nothing to do here.
return NS_OK;
}
}
// From this point on, our image state could change. Watch it.
AutoStateChanger changer(this, aNotify);
// Sanity check.
//
// We use the principal of aDocument to avoid having to QI |this| an extra
// time. It should always be the same as the principal of this node.
#ifdef DEBUG
nsCOMPtr<nsIContent> thisContent = do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
NS_ABORT_IF_FALSE(thisContent &&
thisContent->NodePrincipal() == aDocument->NodePrincipal(),
"Principal mismatch?");
#endif
// Are we blocked?
int16_t cpDecision = nsIContentPolicy::REJECT_REQUEST;
nsContentPolicyType policyType = PolicyTypeForLoad(aImageLoadType);
nsContentUtils::CanLoadImage(aNewURI,
static_cast<nsIImageLoadingContent*>(this),
aDocument,
aDocument->NodePrincipal(),
&cpDecision,
policyType);
if (!NS_CP_ACCEPTED(cpDecision)) {
FireEvent(NS_LITERAL_STRING("error"));
SetBlockedRequest(aNewURI, cpDecision);
return NS_OK;
}
nsLoadFlags loadFlags = aLoadFlags;
int32_t corsmode = GetCORSMode();
if (corsmode == CORS_ANONYMOUS) {
loadFlags |= imgILoader::LOAD_CORS_ANONYMOUS;
} else if (corsmode == CORS_USE_CREDENTIALS) {
loadFlags |= imgILoader::LOAD_CORS_USE_CREDENTIALS;
}
// Not blocked. Do the load.
nsRefPtr<imgRequestProxy>& req = PrepareNextRequest(aImageLoadType);
nsCOMPtr<nsIContent> content =
do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
nsresult rv;
rv = nsContentUtils::LoadImage(aNewURI, aDocument,
aDocument->NodePrincipal(),
aDocument->GetDocumentURI(),
aDocument->GetReferrerPolicy(),
this, loadFlags,
content->LocalName(),
getter_AddRefs(req),
policyType);
// Tell the document to forget about the image preload, if any, for
// this URI, now that we might have another imgRequestProxy for it.
// That way if we get canceled later the image load won't continue.
aDocument->ForgetImagePreload(aNewURI);
if (NS_SUCCEEDED(rv)) {
TrackImage(req);
ResetAnimationIfNeeded();
// Handle cases when we just ended up with a pending request but it's
// already done. In that situation we have to synchronously switch that
// request to being the current request, because websites depend on that
// behavior.
if (req == mPendingRequest) {
uint32_t pendingLoadStatus;
rv = req->GetImageStatus(&pendingLoadStatus);
if (NS_SUCCEEDED(rv) &&
(pendingLoadStatus & imgIRequest::STATUS_LOAD_COMPLETE)) {
MakePendingRequestCurrent();
MOZ_ASSERT(mCurrentRequest,
"How could we not have a current request here?");
nsImageFrame *f = do_QueryFrame(GetOurPrimaryFrame());
if (f) {
f->NotifyNewCurrentRequest(mCurrentRequest, NS_OK);
}
}
}
} else {