- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathTextLayoutStrategy.java
563 lines (508 loc) · 20.8 KB
/
TextLayoutStrategy.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
/*
* Copyright (c) 1999, 2022, 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;
importjava.awt.Container;
importjava.awt.Font;
importjava.awt.Rectangle;
importjava.awt.font.FontRenderContext;
importjava.awt.font.LineBreakMeasurer;
importjava.awt.font.TextAttribute;
importjava.awt.font.TextLayout;
importjava.text.AttributedCharacterIterator;
importjava.text.BreakIterator;
importjava.util.HashSet;
importjava.util.Hashtable;
importjava.util.Map;
importjava.util.Set;
importjavax.swing.JComponent;
importjavax.swing.event.DocumentEvent;
importsun.font.BidiUtils;
/**
* A flow strategy that uses java.awt.font.LineBreakMeasurer to
* produce java.awt.font.TextLayout for i18n capable rendering.
* If the child view being placed into the flow is of type
* GlyphView and can be rendered by TextLayout, a GlyphPainter
* that uses TextLayout is plugged into the GlyphView.
*
* @author Timothy Prinzing
*/
classTextLayoutStrategyextendsFlowView.FlowStrategy {
/**
* Constructs a layout strategy for paragraphs based
* upon java.awt.font.LineBreakMeasurer.
*/
publicTextLayoutStrategy() {
text = newAttributedSegment();
}
// --- FlowStrategy methods --------------------------------------------
/**
* Gives notification that something was inserted into the document
* in a location that the given flow view is responsible for. The
* strategy should update the appropriate changed region (which
* depends upon the strategy used for repair).
*
* @param e the change information from the associated document
* @param alloc the current allocation of the view inside of the insets.
* This value will be null if the view has not yet been displayed.
* @see View#insertUpdate
*/
publicvoidinsertUpdate(FlowViewfv, DocumentEvente, Rectanglealloc) {
sync(fv);
super.insertUpdate(fv, e, alloc);
}
/**
* Gives notification that something was removed from the document
* in a location that the given flow view is responsible for.
*
* @param e the change information from the associated document
* @param alloc the current allocation of the view inside of the insets.
* @see View#removeUpdate
*/
publicvoidremoveUpdate(FlowViewfv, DocumentEvente, Rectanglealloc) {
sync(fv);
super.removeUpdate(fv, e, alloc);
}
/**
* Gives notification from the document that attributes were changed
* in a location that this view is responsible for.
*
* @param e the change information from the associated document
* @param alloc the current allocation of the view inside of the insets.
* @see View#changedUpdate
*/
publicvoidchangedUpdate(FlowViewfv, DocumentEvente, Rectanglealloc) {
sync(fv);
super.changedUpdate(fv, e, alloc);
}
/**
* Does a full layout on the given View. This causes all of
* the rows (child views) to be rebuilt to match the given
* constraints for each row. This is called by FlowView.layout
* to update the child views in the flow.
*
* @param fv the view to reflow
*/
publicvoidlayout(FlowViewfv) {
super.layout(fv);
}
/**
* Creates a row of views that will fit within the
* layout span of the row. This is implemented to execute the
* superclass functionality (which fills the row with child
* views or view fragments) and follow that with bidi reordering
* of the unidirectional view fragments.
*
* @param rowIndex the row to fill in with views. This is assumed
* to be empty on entry.
* @param p0 The current position in the children of
* this view element from which to start.
* @return the position to start the next row
*/
protectedintlayoutRow(FlowViewfv, introwIndex, intp0) {
intp1 = super.layoutRow(fv, rowIndex, p0);
Viewrow = fv.getView(rowIndex);
Documentdoc = fv.getDocument();
Objecti18nFlag = doc.getProperty(AbstractDocument.I18NProperty);
if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) {
intn = row.getViewCount();
if (n > 1) {
AbstractDocumentd = (AbstractDocument)fv.getDocument();
ElementbidiRoot = d.getBidiRootElement();
byte[] levels = newbyte[n];
View[] reorder = newView[n];
for( inti=0; i<n; i++ ) {
Viewv = row.getView(i);
intbidiIndex =bidiRoot.getElementIndex(v.getStartOffset());
ElementbidiElem = bidiRoot.getElement( bidiIndex );
levels[i] = (byte)StyleConstants.getBidiLevel(bidiElem.getAttributes());
reorder[i] = v;
}
BidiUtils.reorderVisually( levels, reorder );
row.replace(0, n, reorder);
}
}
returnp1;
}
/**
* Adjusts the given row if possible to fit within the
* layout span. Since all adjustments were already
* calculated by the LineBreakMeasurer, this is implemented
* to do nothing.
*
* @param rowIndex the row to adjust to the current layout
* span.
* @param desiredSpan the current layout span >= 0
* @param x the location r starts at.
*/
protectedvoidadjustRow(FlowViewfv, introwIndex, intdesiredSpan, intx) {
}
/**
* Creates a unidirectional view that can be used to represent the
* current chunk. This can be either an entire view from the
* logical view, or a fragment of the view.
*
* @param fv the view holding the flow
* @param startOffset the start location for the view being created
* @param spanLeft the amount of span left to fill in the row
* @param rowIndex the row the view will be placed into
*/
protectedViewcreateView(FlowViewfv, intstartOffset, intspanLeft, introwIndex) {
// Get the child view that contains the given starting position
Viewlv = getLogicalView(fv);
Viewrow = fv.getView(rowIndex);
booleanrequireNextWord = (viewBuffer.size() == 0) ? false : true;
intchildIndex = lv.getViewIndex(startOffset, Position.Bias.Forward);
Viewv = lv.getView(childIndex);
intendOffset = getLimitingOffset(v, startOffset, spanLeft, requireNextWord);
if (endOffset == startOffset) {
returnnull;
}
Viewfrag;
if ((startOffset==v.getStartOffset()) && (endOffset == v.getEndOffset())) {
// return the entire view
frag = v;
} else {
// return a unidirectional fragment.
frag = v.createFragment(startOffset, endOffset);
}
if ((fraginstanceofGlyphView) && (measurer != null)) {
// install a TextLayout based renderer if the view is responsible
// for glyphs. If the view represents a tab, the default
// glyph painter is used (may want to handle tabs differently).
booleanisTab = false;
intp0 = frag.getStartOffset();
intp1 = frag.getEndOffset();
if ((p1 - p0) == 1) {
// check for tab
Segments = ((GlyphView)frag).getText(p0, p1);
charch = s.first();
if (ch == '\t') {
isTab = true;
}
}
TextLayouttl = (isTab) ? null :
measurer.nextLayout(spanLeft, text.toIteratorIndex(endOffset),
requireNextWord);
if (tl != null) {
((GlyphView)frag).setGlyphPainter(newGlyphPainter2(tl));
}
}
returnfrag;
}
/**
* Calculate the limiting offset for the next view fragment.
* At most this would be the entire view (i.e. the limiting
* offset would be the end offset in that case). If the range
* contains a tab or a direction change, that will limit the
* offset to something less. This value is then fed to the
* LineBreakMeasurer as a limit to consider in addition to the
* remaining span.
*
* @param v the logical view representing the starting offset.
* @param startOffset the model location to start at.
*/
intgetLimitingOffset(Viewv, intstartOffset, intspanLeft, booleanrequireNextWord) {
intendOffset = v.getEndOffset();
// check for direction change
Documentdoc = v.getDocument();
if (docinstanceofAbstractDocument) {
AbstractDocumentd = (AbstractDocument) doc;
ElementbidiRoot = d.getBidiRootElement();
if( bidiRoot.getElementCount() > 1 ) {
intbidiIndex = bidiRoot.getElementIndex( startOffset );
ElementbidiElem = bidiRoot.getElement( bidiIndex );
endOffset = Math.min( bidiElem.getEndOffset(), endOffset );
}
}
// check for tab
if (vinstanceofGlyphView) {
Segments = ((GlyphView)v).getText(startOffset, endOffset);
charch = s.first();
if (ch == '\t') {
// if the first character is a tab, create a dedicated
// view for just the tab
endOffset = startOffset + 1;
} else {
for (ch = s.next(); ch != Segment.DONE; ch = s.next()) {
if (ch == '\t') {
// found a tab, don't include it in the text
endOffset = startOffset + s.getIndex() - s.getBeginIndex();
break;
}
}
}
}
// determine limit from LineBreakMeasurer
intlimitIndex = text.toIteratorIndex(endOffset);
if (measurer != null) {
intindex = text.toIteratorIndex(startOffset);
if (measurer.getPosition() != index) {
measurer.setPosition(index);
}
limitIndex = measurer.nextOffset(spanLeft, limitIndex, requireNextWord);
}
intpos = text.toModelPosition(limitIndex);
returnpos;
}
/**
* Synchronize the strategy with its FlowView. Allows the strategy
* to update its state to account for changes in that portion of the
* model represented by the FlowView. Also allows the strategy
* to update the FlowView in response to these changes.
*/
voidsync(FlowViewfv) {
Viewlv = getLogicalView(fv);
text.setView(lv);
Containercontainer = fv.getContainer();
FontRenderContextfrc = sun.swing.SwingUtilities2.
getFontRenderContext(container);
BreakIteratoriter;
Containerc = fv.getContainer();
if (c != null) {
iter = BreakIterator.getLineInstance(c.getLocale());
} else {
iter = BreakIterator.getLineInstance();
}
Objectshaper = null;
if (cinstanceofJComponent) {
shaper = ((JComponent) c).getClientProperty(
TextAttribute.NUMERIC_SHAPING);
}
text.setShaper(shaper);
measurer = newLineBreakMeasurer(text, iter, frc);
// If the children of the FlowView's logical view are GlyphViews, they
// need to have their painters updated.
intn = lv.getViewCount();
for( inti=0; i<n; i++ ) {
Viewchild = lv.getView(i);
if( childinstanceofGlyphView ) {
intp0 = child.getStartOffset();
intp1 = child.getEndOffset();
measurer.setPosition(text.toIteratorIndex(p0));
TextLayoutlayout
= measurer.nextLayout( Float.MAX_VALUE,
text.toIteratorIndex(p1), false );
((GlyphView)child).setGlyphPainter(newGlyphPainter2(layout));
}
}
// Reset measurer.
measurer.setPosition(text.getBeginIndex());
}
// --- variables -------------------------------------------------------
privateLineBreakMeasurermeasurer;
privateAttributedSegmenttext;
/**
* Implementation of AttributedCharacterIterator that supports
* the GlyphView attributes for rendering the glyphs through a
* TextLayout.
*/
staticclassAttributedSegmentextendsSegmentimplementsAttributedCharacterIterator {
AttributedSegment() {
}
ViewgetView() {
returnv;
}
voidsetView(Viewv) {
this.v = v;
Documentdoc = v.getDocument();
intp0 = v.getStartOffset();
intp1 = v.getEndOffset();
try {
doc.getText(p0, p1 - p0, this);
} catch (BadLocationExceptionbl) {
thrownewIllegalArgumentException("Invalid view");
}
first();
}
/**
* Get a boundary position for the font.
* This is implemented to assume that two fonts are
* equal if their references are equal (i.e. that the
* font came from a cache).
*
* @return the location in model coordinates. This is
* not the same as the Segment coordinates.
*/
intgetFontBoundary(intchildIndex, intdir) {
Viewchild = v.getView(childIndex);
Fontf = getFont(childIndex);
for (childIndex += dir; (childIndex >= 0) && (childIndex < v.getViewCount());
childIndex += dir) {
Fontnext = getFont(childIndex);
if (next != f) {
// this run is different
break;
}
child = v.getView(childIndex);
}
return (dir < 0) ? child.getStartOffset() : child.getEndOffset();
}
/**
* Get the font at the given child index.
*/
FontgetFont(intchildIndex) {
Viewchild = v.getView(childIndex);
if (childinstanceofGlyphView) {
return ((GlyphView)child).getFont();
}
returnnull;
}
inttoModelPosition(intindex) {
returnv.getStartOffset() + (index - getBeginIndex());
}
inttoIteratorIndex(intpos) {
returnpos - v.getStartOffset() + getBeginIndex();
}
privatevoidsetShaper(Objectshaper) {
this.shaper = shaper;
}
// --- AttributedCharacterIterator methods -------------------------
/**
* Returns the index of the first character of the run
* with respect to all attributes containing the current character.
*/
publicintgetRunStart() {
intpos = toModelPosition(getIndex());
inti = v.getViewIndex(pos, Position.Bias.Forward);
Viewchild = v.getView(i);
returntoIteratorIndex(child.getStartOffset());
}
/**
* Returns the index of the first character of the run
* with respect to the given attribute containing the current character.
*/
publicintgetRunStart(AttributedCharacterIterator.Attributeattribute) {
if (attributeinstanceofTextAttribute) {
intpos = toModelPosition(getIndex());
inti = v.getViewIndex(pos, Position.Bias.Forward);
if (attribute == TextAttribute.FONT) {
returntoIteratorIndex(getFontBoundary(i, -1));
}
}
returngetBeginIndex();
}
/**
* Returns the index of the first character of the run
* with respect to the given attributes containing the current character.
*/
publicintgetRunStart(Set<? extendsAttribute> attributes) {
intindex = getBeginIndex();
Object[] a = attributes.toArray();
for (inti = 0; i < a.length; i++) {
TextAttributeattr = (TextAttribute) a[i];
index = Math.max(getRunStart(attr), index);
}
returnMath.min(getIndex(), index);
}
/**
* Returns the index of the first character following the run
* with respect to all attributes containing the current character.
*/
publicintgetRunLimit() {
intpos = toModelPosition(getIndex());
inti = v.getViewIndex(pos, Position.Bias.Forward);
Viewchild = v.getView(i);
returntoIteratorIndex(child.getEndOffset());
}
/**
* Returns the index of the first character following the run
* with respect to the given attribute containing the current character.
*/
publicintgetRunLimit(AttributedCharacterIterator.Attributeattribute) {
if (attributeinstanceofTextAttribute) {
intpos = toModelPosition(getIndex());
inti = v.getViewIndex(pos, Position.Bias.Forward);
if (attribute == TextAttribute.FONT) {
returntoIteratorIndex(getFontBoundary(i, 1));
}
}
returngetEndIndex();
}
/**
* Returns the index of the first character following the run
* with respect to the given attributes containing the current character.
*/
publicintgetRunLimit(Set<? extendsAttribute> attributes) {
intindex = getEndIndex();
Object[] a = attributes.toArray();
for (inti = 0; i < a.length; i++) {
TextAttributeattr = (TextAttribute) a[i];
index = Math.min(getRunLimit(attr), index);
}
returnMath.max(getIndex(), index);
}
/**
* Returns a map with the attributes defined on the current
* character.
*/
publicMap<Attribute, Object> getAttributes() {
Object[] ka = keys.toArray();
Hashtable<Attribute, Object> h = newHashtable<Attribute, Object>();
for (inti = 0; i < ka.length; i++) {
TextAttributea = (TextAttribute) ka[i];
Objectvalue = getAttribute(a);
if (value != null) {
h.put(a, value);
}
}
returnh;
}
/**
* Returns the value of the named attribute for the current character.
* Returns null if the attribute is not defined.
* @param attribute the key of the attribute whose value is requested.
*/
publicObjectgetAttribute(AttributedCharacterIterator.Attributeattribute) {
intpos = toModelPosition(getIndex());
intchildIndex = v.getViewIndex(pos, Position.Bias.Forward);
if (attribute == TextAttribute.FONT) {
returngetFont(childIndex);
} elseif( attribute == TextAttribute.RUN_DIRECTION ) {
return
v.getDocument().getProperty(TextAttribute.RUN_DIRECTION);
} elseif (attribute == TextAttribute.NUMERIC_SHAPING) {
returnshaper;
}
returnnull;
}
/**
* Returns the keys of all attributes defined on the
* iterator's text range. The set is empty if no
* attributes are defined.
*/
publicSet<Attribute> getAllAttributeKeys() {
returnkeys;
}
Viewv;
staticSet<Attribute> keys;
static {
keys = newHashSet<Attribute>();
keys.add(TextAttribute.FONT);
keys.add(TextAttribute.RUN_DIRECTION);
keys.add(TextAttribute.NUMERIC_SHAPING);
}
privateObjectshaper = null;
}
}