forked from wupeixuan/JDKSourceCode1.8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextLayout.java
More file actions
2762 lines (2435 loc) · 102 KB
/
TextLayout.java
File metadata and controls
2762 lines (2435 loc) · 102 KB
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, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
/*
* (C) Copyright Taligent, Inc. 1996 - 1997, All Rights Reserved
* (C) Copyright IBM Corp. 1996-2003, All Rights Reserved
*
* The original version of this source code and documentation is
* copyrighted and owned by Taligent, Inc., a wholly-owned subsidiary
* of IBM. These materials are provided under terms of a License
* Agreement between Taligent and Sun. This technology is protected
* by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package java.awt.font;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.NumericShaper;
import java.awt.font.TextLine.TextLineMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute;
import java.text.CharacterIterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Hashtable;
import sun.font.AttributeValues;
import sun.font.CoreMetrics;
import sun.font.Decoration;
import sun.font.FontLineMetrics;
import sun.font.FontResolver;
import sun.font.GraphicComponent;
import sun.font.LayoutPathImpl;
import sun.text.CodePointIterator;
/**
*
* <code>TextLayout</code> is an immutable graphical representation of styled
* character data.
* <p>
* It provides the following capabilities:
* <ul>
* <li>implicit bidirectional analysis and reordering,
* <li>cursor positioning and movement, including split cursors for
* mixed directional text,
* <li>highlighting, including both logical and visual highlighting
* for mixed directional text,
* <li>multiple baselines (roman, hanging, and centered),
* <li>hit testing,
* <li>justification,
* <li>default font substitution,
* <li>metric information such as ascent, descent, and advance, and
* <li>rendering
* </ul>
* <p>
* A <code>TextLayout</code> object can be rendered using
* its <code>draw</code> method.
* <p>
* <code>TextLayout</code> can be constructed either directly or through
* the use of a {@link LineBreakMeasurer}. When constructed directly, the
* source text represents a single paragraph. <code>LineBreakMeasurer</code>
* allows styled text to be broken into lines that fit within a particular
* width. See the <code>LineBreakMeasurer</code> documentation for more
* information.
* <p>
* <code>TextLayout</code> construction logically proceeds as follows:
* <ul>
* <li>paragraph attributes are extracted and examined,
* <li>text is analyzed for bidirectional reordering, and reordering
* information is computed if needed,
* <li>text is segmented into style runs
* <li>fonts are chosen for style runs, first by using a font if the
* attribute {@link TextAttribute#FONT} is present, otherwise by computing
* a default font using the attributes that have been defined
* <li>if text is on multiple baselines, the runs or subruns are further
* broken into subruns sharing a common baseline,
* <li>glyphvectors are generated for each run using the chosen font,
* <li>final bidirectional reordering is performed on the glyphvectors
* </ul>
* <p>
* All graphical information returned from a <code>TextLayout</code>
* object's methods is relative to the origin of the
* <code>TextLayout</code>, which is the intersection of the
* <code>TextLayout</code> object's baseline with its left edge. Also,
* coordinates passed into a <code>TextLayout</code> object's methods
* are assumed to be relative to the <code>TextLayout</code> object's
* origin. Clients usually need to translate between a
* <code>TextLayout</code> object's coordinate system and the coordinate
* system in another object (such as a
* {@link java.awt.Graphics Graphics} object).
* <p>
* <code>TextLayout</code> objects are constructed from styled text,
* but they do not retain a reference to their source text. Thus,
* changes in the text previously used to generate a <code>TextLayout</code>
* do not affect the <code>TextLayout</code>.
* <p>
* Three methods on a <code>TextLayout</code> object
* (<code>getNextRightHit</code>, <code>getNextLeftHit</code>, and
* <code>hitTestChar</code>) return instances of {@link TextHitInfo}.
* The offsets contained in these <code>TextHitInfo</code> objects
* are relative to the start of the <code>TextLayout</code>, <b>not</b>
* to the text used to create the <code>TextLayout</code>. Similarly,
* <code>TextLayout</code> methods that accept <code>TextHitInfo</code>
* instances as parameters expect the <code>TextHitInfo</code> object's
* offsets to be relative to the <code>TextLayout</code>, not to any
* underlying text storage model.
* <p>
* <strong>Examples</strong>:<p>
* Constructing and drawing a <code>TextLayout</code> and its bounding
* rectangle:
* <blockquote><pre>
* Graphics2D g = ...;
* Point2D loc = ...;
* Font font = Font.getFont("Helvetica-bold-italic");
* FontRenderContext frc = g.getFontRenderContext();
* TextLayout layout = new TextLayout("This is a string", font, frc);
* layout.draw(g, (float)loc.getX(), (float)loc.getY());
*
* Rectangle2D bounds = layout.getBounds();
* bounds.setRect(bounds.getX()+loc.getX(),
* bounds.getY()+loc.getY(),
* bounds.getWidth(),
* bounds.getHeight());
* g.draw(bounds);
* </pre>
* </blockquote>
* <p>
* Hit-testing a <code>TextLayout</code> (determining which character is at
* a particular graphical location):
* <blockquote><pre>
* Point2D click = ...;
* TextHitInfo hit = layout.hitTestChar(
* (float) (click.getX() - loc.getX()),
* (float) (click.getY() - loc.getY()));
* </pre>
* </blockquote>
* <p>
* Responding to a right-arrow key press:
* <blockquote><pre>
* int insertionIndex = ...;
* TextHitInfo next = layout.getNextRightHit(insertionIndex);
* if (next != null) {
* // translate graphics to origin of layout on screen
* g.translate(loc.getX(), loc.getY());
* Shape[] carets = layout.getCaretShapes(next.getInsertionIndex());
* g.draw(carets[0]);
* if (carets[1] != null) {
* g.draw(carets[1]);
* }
* }
* </pre></blockquote>
* <p>
* Drawing a selection range corresponding to a substring in the source text.
* The selected area may not be visually contiguous:
* <blockquote><pre>
* // selStart, selLimit should be relative to the layout,
* // not to the source text
*
* int selStart = ..., selLimit = ...;
* Color selectionColor = ...;
* Shape selection = layout.getLogicalHighlightShape(selStart, selLimit);
* // selection may consist of disjoint areas
* // graphics is assumed to be tranlated to origin of layout
* g.setColor(selectionColor);
* g.fill(selection);
* </pre></blockquote>
* <p>
* Drawing a visually contiguous selection range. The selection range may
* correspond to more than one substring in the source text. The ranges of
* the corresponding source text substrings can be obtained with
* <code>getLogicalRangesForVisualSelection()</code>:
* <blockquote><pre>
* TextHitInfo selStart = ..., selLimit = ...;
* Shape selection = layout.getVisualHighlightShape(selStart, selLimit);
* g.setColor(selectionColor);
* g.fill(selection);
* int[] ranges = getLogicalRangesForVisualSelection(selStart, selLimit);
* // ranges[0], ranges[1] is the first selection range,
* // ranges[2], ranges[3] is the second selection range, etc.
* </pre></blockquote>
* <p>
* Note: Font rotations can cause text baselines to be rotated, and
* multiple runs with different rotations can cause the baseline to
* bend or zig-zag. In order to account for this (rare) possibility,
* some APIs are specified to return metrics and take parameters 'in
* baseline-relative coordinates' (e.g. ascent, advance), and others
* are in 'in standard coordinates' (e.g. getBounds). Values in
* baseline-relative coordinates map the 'x' coordinate to the
* distance along the baseline, (positive x is forward along the
* baseline), and the 'y' coordinate to a distance along the
* perpendicular to the baseline at 'x' (positive y is 90 degrees
* clockwise from the baseline vector). Values in standard
* coordinates are measured along the x and y axes, with 0,0 at the
* origin of the TextLayout. Documentation for each relevant API
* indicates what values are in what coordinate system. In general,
* measurement-related APIs are in baseline-relative coordinates,
* while display-related APIs are in standard coordinates.
*
* @see LineBreakMeasurer
* @see TextAttribute
* @see TextHitInfo
* @see LayoutPath
*/
public final class TextLayout implements Cloneable {
private int characterCount;
private boolean isVerticalLine = false;
private byte baseline;
private float[] baselineOffsets; // why have these ?
private TextLine textLine;
// cached values computed from GlyphSets and set info:
// all are recomputed from scratch in buildCache()
private TextLine.TextLineMetrics lineMetrics = null;
private float visibleAdvance;
private int hashCodeCache;
/*
* TextLayouts are supposedly immutable. If you mutate a TextLayout under
* the covers (like the justification code does) you'll need to set this
* back to false. Could be replaced with textLine != null <--> cacheIsValid.
*/
private boolean cacheIsValid = false;
// This value is obtained from an attribute, and constrained to the
// interval [0,1]. If 0, the layout cannot be justified.
private float justifyRatio;
// If a layout is produced by justification, then that layout
// cannot be justified. To enforce this constraint the
// justifyRatio of the justified layout is set to this value.
private static final float ALREADY_JUSTIFIED = -53.9f;
// dx and dy specify the distance between the TextLayout's origin
// and the origin of the leftmost GlyphSet (TextLayoutComponent,
// actually). They were used for hanging punctuation support,
// which is no longer implemented. Currently they are both always 0,
// and TextLayout is not guaranteed to work with non-zero dx, dy
// values right now. They were left in as an aide and reminder to
// anyone who implements hanging punctuation or other similar stuff.
// They are static now so they don't take up space in TextLayout
// instances.
private static float dx;
private static float dy;
/*
* Natural bounds is used internally. It is built on demand in
* getNaturalBounds.
*/
private Rectangle2D naturalBounds = null;
/*
* boundsRect encloses all of the bits this TextLayout can draw. It
* is build on demand in getBounds.
*/
private Rectangle2D boundsRect = null;
/*
* flag to supress/allow carets inside of ligatures when hit testing or
* arrow-keying
*/
private boolean caretsInLigaturesAreAllowed = false;
/**
* Defines a policy for determining the strong caret location.
* This class contains one method, <code>getStrongCaret</code>, which
* is used to specify the policy that determines the strong caret in
* dual-caret text. The strong caret is used to move the caret to the
* left or right. Instances of this class can be passed to
* <code>getCaretShapes</code>, <code>getNextLeftHit</code> and
* <code>getNextRightHit</code> to customize strong caret
* selection.
* <p>
* To specify alternate caret policies, subclass <code>CaretPolicy</code>
* and override <code>getStrongCaret</code>. <code>getStrongCaret</code>
* should inspect the two <code>TextHitInfo</code> arguments and choose
* one of them as the strong caret.
* <p>
* Most clients do not need to use this class.
*/
public static class CaretPolicy {
/**
* Constructs a <code>CaretPolicy</code>.
*/
public CaretPolicy() {
}
/**
* Chooses one of the specified <code>TextHitInfo</code> instances as
* a strong caret in the specified <code>TextLayout</code>.
* @param hit1 a valid hit in <code>layout</code>
* @param hit2 a valid hit in <code>layout</code>
* @param layout the <code>TextLayout</code> in which
* <code>hit1</code> and <code>hit2</code> are used
* @return <code>hit1</code> or <code>hit2</code>
* (or an equivalent <code>TextHitInfo</code>), indicating the
* strong caret.
*/
public TextHitInfo getStrongCaret(TextHitInfo hit1,
TextHitInfo hit2,
TextLayout layout) {
// default implementation just calls private method on layout
return layout.getStrongHit(hit1, hit2);
}
}
/**
* This <code>CaretPolicy</code> is used when a policy is not specified
* by the client. With this policy, a hit on a character whose direction
* is the same as the line direction is stronger than a hit on a
* counterdirectional character. If the characters' directions are
* the same, a hit on the leading edge of a character is stronger
* than a hit on the trailing edge of a character.
*/
public static final CaretPolicy DEFAULT_CARET_POLICY = new CaretPolicy();
/**
* Constructs a <code>TextLayout</code> from a <code>String</code>
* and a {@link Font}. All the text is styled using the specified
* <code>Font</code>.
* <p>
* The <code>String</code> must specify a single paragraph of text,
* because an entire paragraph is required for the bidirectional
* algorithm.
* @param string the text to display
* @param font a <code>Font</code> used to style the text
* @param frc contains information about a graphics device which is needed
* to measure the text correctly.
* Text measurements can vary slightly depending on the
* device resolution, and attributes such as antialiasing. This
* parameter does not specify a translation between the
* <code>TextLayout</code> and user space.
*/
public TextLayout(String string, Font font, FontRenderContext frc) {
if (font == null) {
throw new IllegalArgumentException("Null font passed to TextLayout constructor.");
}
if (string == null) {
throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
}
if (string.length() == 0) {
throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
}
Map<? extends Attribute, ?> attributes = null;
if (font.hasLayoutAttributes()) {
attributes = font.getAttributes();
}
char[] text = string.toCharArray();
if (sameBaselineUpTo(font, text, 0, text.length) == text.length) {
fastInit(text, font, attributes, frc);
} else {
AttributedString as = attributes == null
? new AttributedString(string)
: new AttributedString(string, attributes);
as.addAttribute(TextAttribute.FONT, font);
standardInit(as.getIterator(), text, frc);
}
}
/**
* Constructs a <code>TextLayout</code> from a <code>String</code>
* and an attribute set.
* <p>
* All the text is styled using the provided attributes.
* <p>
* <code>string</code> must specify a single paragraph of text because an
* entire paragraph is required for the bidirectional algorithm.
* @param string the text to display
* @param attributes the attributes used to style the text
* @param frc contains information about a graphics device which is needed
* to measure the text correctly.
* Text measurements can vary slightly depending on the
* device resolution, and attributes such as antialiasing. This
* parameter does not specify a translation between the
* <code>TextLayout</code> and user space.
*/
public TextLayout(String string, Map<? extends Attribute,?> attributes,
FontRenderContext frc)
{
if (string == null) {
throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
}
if (attributes == null) {
throw new IllegalArgumentException("Null map passed to TextLayout constructor.");
}
if (string.length() == 0) {
throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
}
char[] text = string.toCharArray();
Font font = singleFont(text, 0, text.length, attributes);
if (font != null) {
fastInit(text, font, attributes, frc);
} else {
AttributedString as = new AttributedString(string, attributes);
standardInit(as.getIterator(), text, frc);
}
}
/*
* Determines a font for the attributes, and if a single font can render
* all the text on one baseline, return it, otherwise null. If the
* attributes specify a font, assume it can display all the text without
* checking.
* If the AttributeSet contains an embedded graphic, return null.
*/
private static Font singleFont(char[] text,
int start,
int limit,
Map<? extends Attribute, ?> attributes) {
if (attributes.get(TextAttribute.CHAR_REPLACEMENT) != null) {
return null;
}
Font font = null;
try {
font = (Font)attributes.get(TextAttribute.FONT);
}
catch (ClassCastException e) {
}
if (font == null) {
if (attributes.get(TextAttribute.FAMILY) != null) {
font = Font.getFont(attributes);
if (font.canDisplayUpTo(text, start, limit) != -1) {
return null;
}
} else {
FontResolver resolver = FontResolver.getInstance();
CodePointIterator iter = CodePointIterator.create(text, start, limit);
int fontIndex = resolver.nextFontRunIndex(iter);
if (iter.charIndex() == limit) {
font = resolver.getFont(fontIndex, attributes);
}
}
}
if (sameBaselineUpTo(font, text, start, limit) != limit) {
return null;
}
return font;
}
/**
* Constructs a <code>TextLayout</code> from an iterator over styled text.
* <p>
* The iterator must specify a single paragraph of text because an
* entire paragraph is required for the bidirectional
* algorithm.
* @param text the styled text to display
* @param frc contains information about a graphics device which is needed
* to measure the text correctly.
* Text measurements can vary slightly depending on the
* device resolution, and attributes such as antialiasing. This
* parameter does not specify a translation between the
* <code>TextLayout</code> and user space.
*/
public TextLayout(AttributedCharacterIterator text, FontRenderContext frc) {
if (text == null) {
throw new IllegalArgumentException("Null iterator passed to TextLayout constructor.");
}
int start = text.getBeginIndex();
int limit = text.getEndIndex();
if (start == limit) {
throw new IllegalArgumentException("Zero length iterator passed to TextLayout constructor.");
}
int len = limit - start;
text.first();
char[] chars = new char[len];
int n = 0;
for (char c = text.first();
c != CharacterIterator.DONE;
c = text.next())
{
chars[n++] = c;
}
text.first();
if (text.getRunLimit() == limit) {
Map<? extends Attribute, ?> attributes = text.getAttributes();
Font font = singleFont(chars, 0, len, attributes);
if (font != null) {
fastInit(chars, font, attributes, frc);
return;
}
}
standardInit(text, chars, frc);
}
/**
* Creates a <code>TextLayout</code> from a {@link TextLine} and
* some paragraph data. This method is used by {@link TextMeasurer}.
* @param textLine the line measurement attributes to apply to the
* the resulting <code>TextLayout</code>
* @param baseline the baseline of the text
* @param baselineOffsets the baseline offsets for this
* <code>TextLayout</code>. This should already be normalized to
* <code>baseline</code>
* @param justifyRatio <code>0</code> if the <code>TextLayout</code>
* cannot be justified; <code>1</code> otherwise.
*/
TextLayout(TextLine textLine,
byte baseline,
float[] baselineOffsets,
float justifyRatio) {
this.characterCount = textLine.characterCount();
this.baseline = baseline;
this.baselineOffsets = baselineOffsets;
this.textLine = textLine;
this.justifyRatio = justifyRatio;
}
/**
* Initialize the paragraph-specific data.
*/
private void paragraphInit(byte aBaseline, CoreMetrics lm,
Map<? extends Attribute, ?> paragraphAttrs,
char[] text) {
baseline = aBaseline;
// normalize to current baseline
baselineOffsets = TextLine.getNormalizedOffsets(lm.baselineOffsets, baseline);
justifyRatio = AttributeValues.getJustification(paragraphAttrs);
NumericShaper shaper = AttributeValues.getNumericShaping(paragraphAttrs);
if (shaper != null) {
shaper.shape(text, 0, text.length);
}
}
/*
* the fast init generates a single glyph set. This requires:
* all one style
* all renderable by one font (ie no embedded graphics)
* all on one baseline
*/
private void fastInit(char[] chars, Font font,
Map<? extends Attribute, ?> attrs,
FontRenderContext frc) {
// Object vf = attrs.get(TextAttribute.ORIENTATION);
// isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
isVerticalLine = false;
LineMetrics lm = font.getLineMetrics(chars, 0, chars.length, frc);
CoreMetrics cm = CoreMetrics.get(lm);
byte glyphBaseline = (byte) cm.baselineIndex;
if (attrs == null) {
baseline = glyphBaseline;
baselineOffsets = cm.baselineOffsets;
justifyRatio = 1.0f;
} else {
paragraphInit(glyphBaseline, cm, attrs, chars);
}
characterCount = chars.length;
textLine = TextLine.fastCreateTextLine(frc, chars, font, cm, attrs);
}
/*
* the standard init generates multiple glyph sets based on style,
* renderable, and baseline runs.
* @param chars the text in the iterator, extracted into a char array
*/
private void standardInit(AttributedCharacterIterator text, char[] chars, FontRenderContext frc) {
characterCount = chars.length;
// set paragraph attributes
{
// If there's an embedded graphic at the start of the
// paragraph, look for the first non-graphic character
// and use it and its font to initialize the paragraph.
// If not, use the first graphic to initialize.
Map<? extends Attribute, ?> paragraphAttrs = text.getAttributes();
boolean haveFont = TextLine.advanceToFirstFont(text);
if (haveFont) {
Font defaultFont = TextLine.getFontAtCurrentPos(text);
int charsStart = text.getIndex() - text.getBeginIndex();
LineMetrics lm = defaultFont.getLineMetrics(chars, charsStart, charsStart+1, frc);
CoreMetrics cm = CoreMetrics.get(lm);
paragraphInit((byte)cm.baselineIndex, cm, paragraphAttrs, chars);
}
else {
// hmmm what to do here? Just try to supply reasonable
// values I guess.
GraphicAttribute graphic = (GraphicAttribute)
paragraphAttrs.get(TextAttribute.CHAR_REPLACEMENT);
byte defaultBaseline = getBaselineFromGraphic(graphic);
CoreMetrics cm = GraphicComponent.createCoreMetrics(graphic);
paragraphInit(defaultBaseline, cm, paragraphAttrs, chars);
}
}
textLine = TextLine.standardCreateTextLine(frc, text, chars, baselineOffsets);
}
/*
* A utility to rebuild the ascent/descent/leading/advance cache.
* You'll need to call this if you clone and mutate (like justification,
* editing methods do)
*/
private void ensureCache() {
if (!cacheIsValid) {
buildCache();
}
}
private void buildCache() {
lineMetrics = textLine.getMetrics();
// compute visibleAdvance
if (textLine.isDirectionLTR()) {
int lastNonSpace = characterCount-1;
while (lastNonSpace != -1) {
int logIndex = textLine.visualToLogical(lastNonSpace);
if (!textLine.isCharSpace(logIndex)) {
break;
}
else {
--lastNonSpace;
}
}
if (lastNonSpace == characterCount-1) {
visibleAdvance = lineMetrics.advance;
}
else if (lastNonSpace == -1) {
visibleAdvance = 0;
}
else {
int logIndex = textLine.visualToLogical(lastNonSpace);
visibleAdvance = textLine.getCharLinePosition(logIndex)
+ textLine.getCharAdvance(logIndex);
}
}
else {
int leftmostNonSpace = 0;
while (leftmostNonSpace != characterCount) {
int logIndex = textLine.visualToLogical(leftmostNonSpace);
if (!textLine.isCharSpace(logIndex)) {
break;
}
else {
++leftmostNonSpace;
}
}
if (leftmostNonSpace == characterCount) {
visibleAdvance = 0;
}
else if (leftmostNonSpace == 0) {
visibleAdvance = lineMetrics.advance;
}
else {
int logIndex = textLine.visualToLogical(leftmostNonSpace);
float pos = textLine.getCharLinePosition(logIndex);
visibleAdvance = lineMetrics.advance - pos;
}
}
// naturalBounds, boundsRect will be generated on demand
naturalBounds = null;
boundsRect = null;
// hashCode will be regenerated on demand
hashCodeCache = 0;
cacheIsValid = true;
}
/**
* The 'natural bounds' encloses all the carets the layout can draw.
*
*/
private Rectangle2D getNaturalBounds() {
ensureCache();
if (naturalBounds == null) {
naturalBounds = textLine.getItalicBounds();
}
return naturalBounds;
}
/**
* Creates a copy of this <code>TextLayout</code>.
*/
protected Object clone() {
/*
* !!! I think this is safe. Once created, nothing mutates the
* glyphvectors or arrays. But we need to make sure.
* {jbr} actually, that's not quite true. The justification code
* mutates after cloning. It doesn't actually change the glyphvectors
* (that's impossible) but it replaces them with justified sets. This
* is a problem for GlyphIterator creation, since new GlyphIterators
* are created by cloning a prototype. If the prototype has outdated
* glyphvectors, so will the new ones. A partial solution is to set the
* prototypical GlyphIterator to null when the glyphvectors change. If
* you forget this one time, you're hosed.
*/
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/*
* Utility to throw an expection if an invalid TextHitInfo is passed
* as a parameter. Avoids code duplication.
*/
private void checkTextHit(TextHitInfo hit) {
if (hit == null) {
throw new IllegalArgumentException("TextHitInfo is null.");
}
if (hit.getInsertionIndex() < 0 ||
hit.getInsertionIndex() > characterCount) {
throw new IllegalArgumentException("TextHitInfo is out of range");
}
}
/**
* Creates a copy of this <code>TextLayout</code> justified to the
* specified width.
* <p>
* If this <code>TextLayout</code> has already been justified, an
* exception is thrown. If this <code>TextLayout</code> object's
* justification ratio is zero, a <code>TextLayout</code> identical
* to this <code>TextLayout</code> is returned.
* @param justificationWidth the width to use when justifying the line.
* For best results, it should not be too different from the current
* advance of the line.
* @return a <code>TextLayout</code> justified to the specified width.
* @exception Error if this layout has already been justified, an Error is
* thrown.
*/
public TextLayout getJustifiedLayout(float justificationWidth) {
if (justificationWidth <= 0) {
throw new IllegalArgumentException("justificationWidth <= 0 passed to TextLayout.getJustifiedLayout()");
}
if (justifyRatio == ALREADY_JUSTIFIED) {
throw new Error("Can't justify again.");
}
ensureCache(); // make sure textLine is not null
// default justification range to exclude trailing logical whitespace
int limit = characterCount;
while (limit > 0 && textLine.isCharWhitespace(limit-1)) {
--limit;
}
TextLine newLine = textLine.getJustifiedLine(justificationWidth, justifyRatio, 0, limit);
if (newLine != null) {
return new TextLayout(newLine, baseline, baselineOffsets, ALREADY_JUSTIFIED);
}
return this;
}
/**
* Justify this layout. Overridden by subclassers to control justification
* (if there were subclassers, that is...)
*
* The layout will only justify if the paragraph attributes (from the
* source text, possibly defaulted by the layout attributes) indicate a
* non-zero justification ratio. The text will be justified to the
* indicated width. The current implementation also adjusts hanging
* punctuation and trailing whitespace to overhang the justification width.
* Once justified, the layout may not be rejustified.
* <p>
* Some code may rely on immutablity of layouts. Subclassers should not
* call this directly, but instead should call getJustifiedLayout, which
* will call this method on a clone of this layout, preserving
* the original.
*
* @param justificationWidth the width to use when justifying the line.
* For best results, it should not be too different from the current
* advance of the line.
* @see #getJustifiedLayout(float)
*/
protected void handleJustify(float justificationWidth) {
// never called
}
/**
* Returns the baseline for this <code>TextLayout</code>.
* The baseline is one of the values defined in <code>Font</code>,
* which are roman, centered and hanging. Ascent and descent are
* relative to this baseline. The <code>baselineOffsets</code>
* are also relative to this baseline.
* @return the baseline of this <code>TextLayout</code>.
* @see #getBaselineOffsets()
* @see Font
*/
public byte getBaseline() {
return baseline;
}
/**
* Returns the offsets array for the baselines used for this
* <code>TextLayout</code>.
* <p>
* The array is indexed by one of the values defined in
* <code>Font</code>, which are roman, centered and hanging. The
* values are relative to this <code>TextLayout</code> object's
* baseline, so that <code>getBaselineOffsets[getBaseline()] == 0</code>.
* Offsets are added to the position of the <code>TextLayout</code>
* object's baseline to get the position for the new baseline.
* @return the offsets array containing the baselines used for this
* <code>TextLayout</code>.
* @see #getBaseline()
* @see Font
*/
public float[] getBaselineOffsets() {
float[] offsets = new float[baselineOffsets.length];
System.arraycopy(baselineOffsets, 0, offsets, 0, offsets.length);
return offsets;
}
/**
* Returns the advance of this <code>TextLayout</code>.
* The advance is the distance from the origin to the advance of the
* rightmost (bottommost) character. This is in baseline-relative
* coordinates.
* @return the advance of this <code>TextLayout</code>.
*/
public float getAdvance() {
ensureCache();
return lineMetrics.advance;
}
/**
* Returns the advance of this <code>TextLayout</code>, minus trailing
* whitespace. This is in baseline-relative coordinates.
* @return the advance of this <code>TextLayout</code> without the
* trailing whitespace.
* @see #getAdvance()
*/
public float getVisibleAdvance() {
ensureCache();
return visibleAdvance;
}
/**
* Returns the ascent of this <code>TextLayout</code>.
* The ascent is the distance from the top (right) of the
* <code>TextLayout</code> to the baseline. It is always either
* positive or zero. The ascent is sufficient to
* accommodate superscripted text and is the maximum of the sum of the
* ascent, offset, and baseline of each glyph. The ascent is
* the maximum ascent from the baseline of all the text in the
* TextLayout. It is in baseline-relative coordinates.
* @return the ascent of this <code>TextLayout</code>.
*/
public float getAscent() {
ensureCache();
return lineMetrics.ascent;
}
/**
* Returns the descent of this <code>TextLayout</code>.
* The descent is the distance from the baseline to the bottom (left) of
* the <code>TextLayout</code>. It is always either positive or zero.
* The descent is sufficient to accommodate subscripted text and is the
* maximum of the sum of the descent, offset, and baseline of each glyph.
* This is the maximum descent from the baseline of all the text in
* the TextLayout. It is in baseline-relative coordinates.
* @return the descent of this <code>TextLayout</code>.
*/
public float getDescent() {
ensureCache();
return lineMetrics.descent;
}
/**
* Returns the leading of the <code>TextLayout</code>.
* The leading is the suggested interline spacing for this
* <code>TextLayout</code>. This is in baseline-relative
* coordinates.
* <p>
* The leading is computed from the leading, descent, and baseline
* of all glyphvectors in the <code>TextLayout</code>. The algorithm
* is roughly as follows:
* <blockquote><pre>
* maxD = 0;
* maxDL = 0;
* for (GlyphVector g in all glyphvectors) {
* maxD = max(maxD, g.getDescent() + offsets[g.getBaseline()]);
* maxDL = max(maxDL, g.getDescent() + g.getLeading() +
* offsets[g.getBaseline()]);
* }
* return maxDL - maxD;
* </pre></blockquote>
* @return the leading of this <code>TextLayout</code>.
*/
public float getLeading() {
ensureCache();
return lineMetrics.leading;
}
/**
* Returns the bounds of this <code>TextLayout</code>.
* The bounds are in standard coordinates.
* <p>Due to rasterization effects, this bounds might not enclose all of the
* pixels rendered by the TextLayout.</p>
* It might not coincide exactly with the ascent, descent,
* origin or advance of the <code>TextLayout</code>.
* @return a {@link Rectangle2D} that is the bounds of this
* <code>TextLayout</code>.
*/
public Rectangle2D getBounds() {
ensureCache();
if (boundsRect == null) {
Rectangle2D vb = textLine.getVisualBounds();
if (dx != 0 || dy != 0) {
vb.setRect(vb.getX() - dx,
vb.getY() - dy,
vb.getWidth(),
vb.getHeight());
}
boundsRect = vb;
}
Rectangle2D bounds = new Rectangle2D.Float();
bounds.setRect(boundsRect);
return bounds;
}
/**
* Returns the pixel bounds of this <code>TextLayout</code> when
* rendered in a graphics with the given
* <code>FontRenderContext</code> at the given location. The