- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathImageView.java
1119 lines (1014 loc) · 37 KB
/
ImageView.java
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
/*
* Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
packagejavax.swing.text.html;
importjava.awt.Rectangle;
importjava.awt.Image;
importjava.awt.Dimension;
importjava.awt.Container;
importjava.awt.Color;
importjava.awt.Shape;
importjava.awt.Graphics;
importjava.awt.Toolkit;
importjava.awt.image.ImageObserver;
importjava.net.URL;
importjava.net.MalformedURLException;
importjava.util.Dictionary;
importjavax.swing.GrayFilter;
importjavax.swing.ImageIcon;
importjavax.swing.Icon;
importjavax.swing.UIManager;
importjavax.swing.SwingUtilities;
importjavax.swing.text.JTextComponent;
importjavax.swing.text.StyledDocument;
importjavax.swing.text.View;
importjavax.swing.text.AttributeSet;
importjavax.swing.text.Element;
importjavax.swing.text.ViewFactory;
importjavax.swing.text.Position;
importjavax.swing.text.Segment;
importjavax.swing.text.Highlighter;
importjavax.swing.text.LayeredHighlighter;
importjavax.swing.text.AbstractDocument;
importjavax.swing.text.Document;
importjavax.swing.text.BadLocationException;
importjavax.swing.event.DocumentEvent;
/**
* View of an Image, intended to support the HTML <IMG> tag.
* Supports scaling via the HEIGHT and WIDTH attributes of the tag.
* If the image is unable to be loaded any text specified via the
* <code>ALT</code> attribute will be rendered.
* <p>
* While this class has been part of swing for a while now, it is public
* as of 1.4.
*
* @author Scott Violet
* @see javax.swing.text.IconView
* @since 1.4
*/
publicclassImageViewextendsView {
/**
* If true, when some of the bits are available a repaint is done.
* <p>
* This is set to false as swing does not offer a repaint that takes a
* delay. If this were true, a bunch of immediate repaints would get
* generated that end up significantly delaying the loading of the image
* (or anything else going on for that matter).
*/
privatestaticbooleansIsInc = false;
/**
* Repaint delay when some of the bits are available.
*/
privatestaticintsIncRate = 100;
/**
* Property name for pending image icon
*/
privatestaticfinalStringPENDING_IMAGE = "html.pendingImage";
/**
* Property name for missing image icon
*/
privatestaticfinalStringMISSING_IMAGE = "html.missingImage";
/**
* Document property for image cache.
*/
privatestaticfinalStringIMAGE_CACHE_PROPERTY = "imageCache";
// Height/width to use before we know the real size, these should at least
// the size of <code>sMissingImageIcon</code> and
// <code>sPendingImageIcon</code>
privatestaticfinalintDEFAULT_WIDTH = 38;
privatestaticfinalintDEFAULT_HEIGHT= 38;
/**
* Default border to use if one is not specified.
*/
privatestaticfinalintDEFAULT_BORDER = 2;
// Bitmask values
privatestaticfinalintLOADING_FLAG = 1;
privatestaticfinalintLINK_FLAG = 2;
privatestaticfinalintWIDTH_FLAG = 4;
privatestaticfinalintHEIGHT_FLAG = 8;
privatestaticfinalintRELOAD_FLAG = 16;
privatestaticfinalintRELOAD_IMAGE_FLAG = 32;
privatestaticfinalintSYNC_LOAD_FLAG = 64;
privateAttributeSetattr;
privateImageimage;
privateImagedisabledImage;
privateintwidth;
privateintheight;
/** Bitmask containing some of the above bitmask values. Because the
* image loading notification can happen on another thread access to
* this is synchronized (at least for modifying it). */
privateintstate;
privateContainercontainer;
privateRectanglefBounds;
privateColorborderColor;
// Size of the border, the insets contains this valid. For example, if
// the HSPACE attribute was 4 and BORDER 2, leftInset would be 6.
privateshortborderSize;
// Insets, obtained from the painter.
privateshortleftInset;
privateshortrightInset;
privateshorttopInset;
privateshortbottomInset;
/**
* We don't directly implement ImageObserver, instead we use an instance
* that calls back to us.
*/
privateImageObserverimageObserver;
/**
* Used for alt text. Will be non-null if the image couldn't be found,
* and there is valid alt text.
*/
privateViewaltView;
/** Alignment along the vertical (Y) axis. */
privatefloatvAlign;
/**
* Creates a new view that represents an IMG element.
*
* @param elem the element to create a view for
*/
publicImageView(Elementelem) {
super(elem);
fBounds = newRectangle();
imageObserver = newImageHandler();
state = RELOAD_FLAG | RELOAD_IMAGE_FLAG;
}
/**
* Returns the text to display if the image cannot be loaded. This is
* obtained from the Elements attribute set with the attribute name
* <code>HTML.Attribute.ALT</code>.
*
* @return the test to display if the image cannot be loaded.
*/
publicStringgetAltText() {
return (String)getElement().getAttributes().getAttribute
(HTML.Attribute.ALT);
}
/**
* Return a URL for the image source,
* or null if it could not be determined.
*
* @return the URL for the image source, or null if it could not be determined.
*/
publicURLgetImageURL() {
Stringsrc = (String)getElement().getAttributes().
getAttribute(HTML.Attribute.SRC);
if (src == null) {
returnnull;
}
URLreference = ((HTMLDocument)getDocument()).getBase();
try {
@SuppressWarnings("deprecation")
URLu = newURL(reference,src);
returnu;
} catch (MalformedURLExceptione) {
returnnull;
}
}
/**
* Returns the icon to use if the image could not be found.
*
* @return the icon to use if the image could not be found.
*/
publicIcongetNoImageIcon() {
return (Icon) UIManager.getLookAndFeelDefaults().get(MISSING_IMAGE);
}
/**
* Returns the icon to use while in the process of loading the image.
*
* @return the icon to use while in the process of loading the image.
*/
publicIcongetLoadingImageIcon() {
return (Icon) UIManager.getLookAndFeelDefaults().get(PENDING_IMAGE);
}
/**
* Returns the image to render.
*
* @return the image to render.
*/
publicImagegetImage() {
sync();
returnimage;
}
privateImagegetImage(booleanenabled) {
Imageimg = getImage();
if (! enabled) {
if (disabledImage == null) {
disabledImage = GrayFilter.createDisabledImage(img);
}
img = disabledImage;
}
returnimg;
}
/**
* Sets how the image is loaded. If <code>newValue</code> is true,
* the image will be loaded when first asked for, otherwise it will
* be loaded asynchronously. The default is to not load synchronously,
* that is to load the image asynchronously.
*
* @param newValue if {@code true} the image will be loaded when first asked for,
* otherwise it will be asynchronously.
*/
publicvoidsetLoadsSynchronously(booleannewValue) {
synchronized(this) {
if (newValue) {
state |= SYNC_LOAD_FLAG;
}
else {
state = (state | SYNC_LOAD_FLAG) ^ SYNC_LOAD_FLAG;
}
}
}
/**
* Returns {@code true} if the image should be loaded when first asked for.
*
* @return {@code true} if the image should be loaded when first asked for.
*/
publicbooleangetLoadsSynchronously() {
return ((state & SYNC_LOAD_FLAG) != 0);
}
/**
* Convenient method to get the StyleSheet.
*
* @return the StyleSheet
*/
protectedStyleSheetgetStyleSheet() {
HTMLDocumentdoc = (HTMLDocument) getDocument();
returndoc.getStyleSheet();
}
/**
* Fetches the attributes to use when rendering. This is
* implemented to multiplex the attributes specified in the
* model with a StyleSheet.
*/
publicAttributeSetgetAttributes() {
sync();
returnattr;
}
/**
* For images the tooltip text comes from text specified with the
* <code>ALT</code> attribute. This is overridden to return
* <code>getAltText</code>.
*
* @see JTextComponent#getToolTipText
*/
publicStringgetToolTipText(floatx, floaty, Shapeallocation) {
returngetAltText();
}
/**
* Update any cached values that come from attributes.
*/
protectedvoidsetPropertiesFromAttributes() {
StyleSheetsheet = getStyleSheet();
this.attr = sheet.getViewAttributes(this);
// Gutters
borderSize = (short)getIntAttr(HTML.Attribute.BORDER, isLink() ?
DEFAULT_BORDER : 0);
leftInset = rightInset = (short)(getIntAttr(HTML.Attribute.HSPACE,
0) + borderSize);
topInset = bottomInset = (short)(getIntAttr(HTML.Attribute.VSPACE,
0) + borderSize);
borderColor = ((StyledDocument)getDocument()).getForeground
(getAttributes());
AttributeSetattr = getElement().getAttributes();
// Alignment.
// PENDING: This needs to be changed to support the CSS versions
// when conversion from ALIGN to VERTICAL_ALIGN is complete.
Objectalignment = attr.getAttribute(HTML.Attribute.ALIGN);
vAlign = 1.0f;
if (alignment != null) {
alignment = alignment.toString();
if ("top".equals(alignment)) {
vAlign = 0f;
}
elseif ("middle".equals(alignment)) {
vAlign = .5f;
}
}
AttributeSetanchorAttr = (AttributeSet)attr.getAttribute(HTML.Tag.A);
if (anchorAttr != null && anchorAttr.isDefined
(HTML.Attribute.HREF)) {
synchronized(this) {
state |= LINK_FLAG;
}
}
else {
synchronized(this) {
state = (state | LINK_FLAG) ^ LINK_FLAG;
}
}
}
/**
* Establishes the parent view for this view.
* Seize this moment to cache the AWT Container I'm in.
*/
publicvoidsetParent(Viewparent) {
ViewoldParent = getParent();
super.setParent(parent);
container = (parent != null) ? getContainer() : null;
if (oldParent != parent) {
synchronized(this) {
state |= RELOAD_FLAG;
}
}
}
/**
* Invoked when the Elements attributes have changed. Recreates the image.
*/
publicvoidchangedUpdate(DocumentEvente, Shapea, ViewFactoryf) {
super.changedUpdate(e,a,f);
synchronized(this) {
state |= RELOAD_FLAG | RELOAD_IMAGE_FLAG;
}
// Assume the worst.
preferenceChanged(null, true, true);
}
/**
* Paints the View.
*
* @param g the rendering surface to use
* @param a the allocated region to render into
* @see View#paint
*/
publicvoidpaint(Graphicsg, Shapea) {
sync();
Rectanglerect = (ainstanceofRectangle) ? (Rectangle)a :
a.getBounds();
Rectangleclip = g.getClipBounds();
fBounds.setBounds(rect);
paintHighlights(g, a);
paintBorder(g, rect);
if (clip != null) {
g.clipRect(rect.x + leftInset, rect.y + topInset,
rect.width - leftInset - rightInset,
rect.height - topInset - bottomInset);
}
Containerhost = getContainer();
Imageimg = getImage(host == null || host.isEnabled());
if (img != null) {
if (! hasPixels(img)) {
// No pixels yet, use the default
Iconicon = getLoadingImageIcon();
if (icon != null) {
icon.paintIcon(host, g,
rect.x + leftInset, rect.y + topInset);
}
}
else {
// Draw the image
g.drawImage(img, rect.x + leftInset, rect.y + topInset,
width, height, imageObserver);
}
}
else {
Iconicon = getNoImageIcon();
if (icon != null) {
icon.paintIcon(host, g,
rect.x + leftInset, rect.y + topInset);
}
Viewview = getAltView();
// Paint the view representing the alt text, if its non-null
if (view != null && ((state & WIDTH_FLAG) == 0 ||
width > DEFAULT_WIDTH)) {
// Assume layout along the y direction
RectanglealtRect = newRectangle
(rect.x + leftInset + DEFAULT_WIDTH, rect.y + topInset,
rect.width - leftInset - rightInset - DEFAULT_WIDTH,
rect.height - topInset - bottomInset);
view.paint(g, altRect);
}
}
if (clip != null) {
// Reset clip.
g.setClip(clip.x, clip.y, clip.width, clip.height);
}
}
privatevoidpaintHighlights(Graphicsg, Shapeshape) {
if (containerinstanceofJTextComponent) {
JTextComponenttc = (JTextComponent)container;
Highlighterh = tc.getHighlighter();
if (hinstanceofLayeredHighlighter) {
((LayeredHighlighter)h).paintLayeredHighlights
(g, getStartOffset(), getEndOffset(), shape, tc, this);
}
}
}
privatevoidpaintBorder(Graphicsg, Rectanglerect) {
Colorcolor = borderColor;
if ((borderSize > 0 || image == null) && color != null) {
intxOffset = leftInset - borderSize;
intyOffset = topInset - borderSize;
g.setColor(color);
intn = (image == null) ? 1 : borderSize;
for (intcounter = 0; counter < n; counter++) {
g.drawRect(rect.x + xOffset + counter,
rect.y + yOffset + counter,
rect.width - counter - counter - xOffset -xOffset-1,
rect.height - counter - counter -yOffset-yOffset-1);
}
}
}
/**
* Determines the preferred span for this view along an
* axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the span the view would like to be rendered into;
* typically the view is told to render into the span
* that is returned, although there is no guarantee;
* the parent may choose to resize or break the view
*/
publicfloatgetPreferredSpan(intaxis) {
sync();
// If the attributes specified a width/height, always use it!
if (axis == View.X_AXIS && (state & WIDTH_FLAG) == WIDTH_FLAG) {
getPreferredSpanFromAltView(axis);
returnwidth + leftInset + rightInset;
}
if (axis == View.Y_AXIS && (state & HEIGHT_FLAG) == HEIGHT_FLAG) {
getPreferredSpanFromAltView(axis);
returnheight + topInset + bottomInset;
}
Imageimage = getImage();
if (image != null) {
switch (axis) {
caseView.X_AXIS:
returnwidth + leftInset + rightInset;
caseView.Y_AXIS:
returnheight + topInset + bottomInset;
default:
thrownewIllegalArgumentException("Invalid axis: " + axis);
}
}
else {
Viewview = getAltView();
floatretValue = 0f;
if (view != null) {
retValue = view.getPreferredSpan(axis);
}
switch (axis) {
caseView.X_AXIS:
returnretValue + (float)(width + leftInset + rightInset);
caseView.Y_AXIS:
returnretValue + (float)(height + topInset + bottomInset);
default:
thrownewIllegalArgumentException("Invalid axis: " + axis);
}
}
}
/**
* Determines the desired alignment for this view along an
* axis. This is implemented to give the alignment to the
* bottom of the icon along the y axis, and the default
* along the x axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the desired alignment; this should be a value
* between 0.0 and 1.0 where 0 indicates alignment at the
* origin and 1.0 indicates alignment to the full span
* away from the origin; an alignment of 0.5 would be the
* center of the view
*/
publicfloatgetAlignment(intaxis) {
switch (axis) {
caseView.Y_AXIS:
returnvAlign;
default:
returnsuper.getAlignment(axis);
}
}
/**
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param pos the position to convert
* @param a the allocated region to render into
* @return the bounding box of the given position
* @throws BadLocationException if the given position does not represent a
* valid location in the associated document
* @see View#modelToView
*/
publicShapemodelToView(intpos, Shapea, Position.Biasb) throwsBadLocationException {
intp0 = getStartOffset();
intp1 = getEndOffset();
if ((pos >= p0) && (pos <= p1)) {
Rectangler = a.getBounds();
if (pos == p1) {
r.x += r.width;
}
r.width = 0;
returnr;
}
returnnull;
}
/**
* Provides a mapping from the view coordinate space to the logical
* coordinate space of the model.
*
* @param x the X coordinate
* @param y the Y coordinate
* @param a the allocated region to render into
* @return the location within the model that best represents the
* given point of view
* @see View#viewToModel
*/
publicintviewToModel(floatx, floaty, Shapea, Position.Bias[] bias) {
Rectanglealloc = (Rectangle) a;
if (x < alloc.x + alloc.width) {
bias[0] = Position.Bias.Forward;
returngetStartOffset();
}
bias[0] = Position.Bias.Backward;
returngetEndOffset();
}
/**
* Sets the size of the view. This should cause
* layout of the view if it has any layout duties.
*
* @param width the width >= 0
* @param height the height >= 0
*/
publicvoidsetSize(floatwidth, floatheight) {
sync();
if (getImage() == null) {
Viewview = getAltView();
if (view != null) {
view.setSize(Math.max(0f, width - (float)(DEFAULT_WIDTH + leftInset + rightInset)),
Math.max(0f, height - (float)(topInset + bottomInset)));
}
}
}
/**
* Returns true if this image within a link?
*/
privatebooleanisLink() {
return ((state & LINK_FLAG) == LINK_FLAG);
}
/**
* Returns true if the passed in image has a non-zero width and height.
*/
privatebooleanhasPixels(Imageimage) {
returnimage != null &&
(image.getHeight(imageObserver) > 0) &&
(image.getWidth(imageObserver) > 0);
}
/**
* Returns the preferred span of the View used to display the alt text,
* or 0 if the view does not exist.
*/
privatefloatgetPreferredSpanFromAltView(intaxis) {
if (getImage() == null) {
Viewview = getAltView();
if (view != null) {
returnview.getPreferredSpan(axis);
}
}
return0f;
}
/**
* Request that this view be repainted.
* Assumes the view is still at its last-drawn location.
*/
privatevoidrepaint(longdelay) {
if (container != null && fBounds != null) {
container.repaint(delay, fBounds.x, fBounds.y, fBounds.width,
fBounds.height);
}
}
/**
* Convenient method for getting an integer attribute from the elements
* AttributeSet.
*/
privateintgetIntAttr(HTML.Attributename, intdeflt) {
AttributeSetattr = getElement().getAttributes();
if (attr.isDefined(name)) { // does not check parents!
inti;
Stringval = (String)attr.getAttribute(name);
if (val == null) {
i = deflt;
}
else {
try{
i = Math.max(0, Integer.parseInt(val));
}catch( NumberFormatExceptionx ) {
i = deflt;
}
}
returni;
} else
returndeflt;
}
/**
* Makes sure the necessary properties and image is loaded.
*/
privatevoidsync() {
ints = state;
if ((s & RELOAD_IMAGE_FLAG) != 0) {
refreshImage();
}
s = state;
if ((s & RELOAD_FLAG) != 0) {
synchronized(this) {
state = (state | RELOAD_FLAG) ^ RELOAD_FLAG;
}
setPropertiesFromAttributes();
}
}
/**
* Loads the image and updates the size accordingly. This should be
* invoked instead of invoking <code>loadImage</code> or
* <code>updateImageSize</code> directly.
*/
privatevoidrefreshImage() {
synchronized(this) {
// clear out width/height/realoadimage flag and set loading flag
state = (state | LOADING_FLAG | RELOAD_IMAGE_FLAG | WIDTH_FLAG |
HEIGHT_FLAG) ^ (WIDTH_FLAG | HEIGHT_FLAG |
RELOAD_IMAGE_FLAG);
image = null;
width = height = 0;
}
try {
// Load the image
loadImage();
// And update the size params
updateImageSize();
}
finally {
synchronized(this) {
// Clear out state in case someone threw an exception.
state = (state | LOADING_FLAG) ^ LOADING_FLAG;
}
}
}
/**
* Loads the image from the URL <code>getImageURL</code>. This should
* only be invoked from <code>refreshImage</code>.
*/
privatevoidloadImage() {
URLsrc = getImageURL();
ImagenewImage = null;
if (src != null) {
@SuppressWarnings("unchecked")
Dictionary<URL, Image> cache = (Dictionary)getDocument().
getProperty(IMAGE_CACHE_PROPERTY);
if (cache != null) {
newImage = cache.get(src);
}
else {
newImage = Toolkit.getDefaultToolkit().createImage(src);
if (newImage != null && getLoadsSynchronously()) {
// Force the image to be loaded by using an ImageIcon.
ImageIconii = newImageIcon();
ii.setImage(newImage);
}
}
}
image = newImage;
}
/**
* Recreates and reloads the image. This should
* only be invoked from <code>refreshImage</code>.
*/
privatevoidupdateImageSize() {
intnewWidth = 0;
intnewHeight = 0;
intnewState = 0;
ImagenewImage = getImage();
if (newImage != null) {
Elementelem = getElement();
AttributeSetattr = elem.getAttributes();
// Get the width/height and set the state ivar before calling
// anything that might cause the image to be loaded, and thus the
// ImageHandler to be called.
newWidth = getIntAttr(HTML.Attribute.WIDTH, -1);
newHeight = getIntAttr(HTML.Attribute.HEIGHT, -1);
if (newWidth > 0) {
newState |= WIDTH_FLAG;
}
if (newHeight > 0) {
newState |= HEIGHT_FLAG;
}
Imageimg;
synchronized(this) {
img = image;
}
if (newWidth <= 0) {
newWidth = img.getWidth(imageObserver);
if (newWidth <= 0) {
newWidth = DEFAULT_WIDTH;
}
}
if (newHeight <= 0) {
newHeight = img.getHeight(imageObserver);
if (newHeight <= 0) {
newHeight = DEFAULT_HEIGHT;
}
}
/*
If synchronous loading flag is set, then make sure that the image is
scaled appropriately.
Otherwise, the ImageHandler::imageUpdate takes care of scaling the image
appropriately.
*/
if (getLoadsSynchronously()) {
Dimensiond = adjustWidthHeight(newWidth, newHeight);
newWidth = d.width;
newHeight = d.height;
newState |= (WIDTH_FLAG | HEIGHT_FLAG);
}
// Make sure the image starts loading:
if ((newState & (WIDTH_FLAG | HEIGHT_FLAG)) != 0) {
Toolkit.getDefaultToolkit().prepareImage(newImage, newWidth,
newHeight,
imageObserver);
}
else {
Toolkit.getDefaultToolkit().prepareImage(newImage, -1, -1,
imageObserver);
}
booleancreateText = false;
synchronized(this) {
// If imageloading failed, other thread may have called
// ImageLoader which will null out image, hence we check
// for it.
if (image != null) {
if ((newState & WIDTH_FLAG) == WIDTH_FLAG || width == 0) {
width = newWidth;
}
if ((newState & HEIGHT_FLAG) == HEIGHT_FLAG ||
height == 0) {
height = newHeight;
}
}
else {
createText = true;
if ((newState & WIDTH_FLAG) == WIDTH_FLAG) {
width = newWidth;
}
if ((newState & HEIGHT_FLAG) == HEIGHT_FLAG) {
height = newHeight;
}
}
state = state | newState;
state = (state | LOADING_FLAG) ^ LOADING_FLAG;
}
if (createText) {
// Only reset if this thread determined image is null
updateAltTextView();
}
}
else {
width = height = DEFAULT_HEIGHT;
updateAltTextView();
}
}
/**
* Updates the view representing the alt text.
*/
privatevoidupdateAltTextView() {
Stringtext = getAltText();
if (text != null) {
ImageLabelViewnewView;
newView = newImageLabelView(getElement(), text);
synchronized(this) {
altView = newView;
}
}
}
/**
* Returns the view to use for alternate text. This may be null.
*/
privateViewgetAltView() {
Viewview;
synchronized(this) {
view = altView;
}
if (view != null && view.getParent() == null) {
view.setParent(getParent());
}
returnview;
}
/**
* Invokes <code>preferenceChanged</code> on the event dispatching
* thread.
*/
privatevoidsafePreferenceChanged() {
if (SwingUtilities.isEventDispatchThread()) {
Documentdoc = getDocument();
if (docinstanceofAbstractDocument) {
((AbstractDocument)doc).readLock();
}
preferenceChanged(null, true, true);
if (docinstanceofAbstractDocument) {
((AbstractDocument)doc).readUnlock();
}
}
else {
SwingUtilities.invokeLater(newRunnable() {
publicvoidrun() {
safePreferenceChanged();
}
});
}
}
privateDimensionadjustWidthHeight(intnewWidth, intnewHeight) {
Dimensiond = newDimension();
doubleproportion = 0.0;
finalintspecifiedWidth = getIntAttr(HTML.Attribute.WIDTH, -1);
finalintspecifiedHeight = getIntAttr(HTML.Attribute.HEIGHT, -1);
/**
* If either of the attributes are not specified, then calculate the
* proportion for the specified dimension wrt actual value, and then
* apply the same proportion to the unspecified dimension as well,
* so that the aspect ratio of the image is maintained.
*/
if (specifiedWidth != -1 && specifiedHeight != -1) {
newWidth = specifiedWidth;
newHeight = specifiedHeight;
} elseif (specifiedWidth != -1 ^ specifiedHeight != -1) {
if (specifiedWidth <= 0) {
proportion = specifiedHeight / ((double)newHeight);
newWidth = (int)(proportion * newWidth);
newHeight = specifiedHeight;
}
if (specifiedHeight <= 0) {
proportion = specifiedWidth / ((double)newWidth);
newHeight = (int)(proportion * newHeight);
newWidth = specifiedWidth;
}
}
d.width = newWidth;
d.height = newHeight;
returnd;
}
/**
* ImageHandler implements the ImageObserver to correctly update the
* display as new parts of the image become available.
*/
privateclassImageHandlerimplementsImageObserver {
// This can come on any thread. If we are in the process of reloading
// the image and determining our state (loading == true) we don't fire
// preference changed, or repaint, we just reset the fWidth/fHeight as
// necessary and return. This is ok as we know when loading finishes
// it will pick up the new height/width, if necessary.
publicbooleanimageUpdate(Imageimg, intflags, intx, inty,
intnewWidth, intnewHeight ) {
if (img != image && img != disabledImage ||
image == null || getParent() == null) {
returnfalse;
}
// Bail out if there was an error:
if ((flags & (ABORT|ERROR)) != 0) {
repaint(0);
synchronized(ImageView.this) {
if (image == img) {
// Be sure image hasn't changed since we don't
// initially synchronize
image = null;
if ((state & WIDTH_FLAG) != WIDTH_FLAG) {
width = DEFAULT_WIDTH;
}
if ((state & HEIGHT_FLAG) != HEIGHT_FLAG) {
height = DEFAULT_HEIGHT;
}
} else {
disabledImage = null;
}
if ((state & LOADING_FLAG) == LOADING_FLAG) {
// No need to resize or repaint, still in the process
// of loading.
returnfalse;
}
}
updateAltTextView();
safePreferenceChanged();
returnfalse;
}
if (image == img) {
// Resize image if necessary: